Skip to content
This repository has been archived by the owner on Feb 13, 2020. It is now read-only.

Key-based mutex #126

Open
jcornaz opened this issue Feb 26, 2019 · 0 comments
Open

Key-based mutex #126

jcornaz opened this issue Feb 26, 2019 · 0 comments
Labels
feature Add a new feature need-usecase This lacks of use-case for now. It has to be motivated by a concrete need before being implemented.

Comments

@jcornaz
Copy link
Owner

jcornaz commented Feb 26, 2019

Draft:

class KeyBasedMutex<in K>(size: Int) {

  private val mutexes = List(size) { Mutex() }

  init {
    require(size > 0)
  }

  suspend fun lock(key: K) {
    mutexes[key.hashCode() % mutexes.size].lock()
  }

  fun unlock(key: K) {
    mutexes[key.hashCode() % mutexes.size].unlock()
  }
}

suspend inline fun <K, R> KeyBasedMutex<K>.withLock(key: K, block: () -> R): R {
  lock(key)
  return try {
    block()
  } finally {
    unlock(key)
  }
}
@jcornaz jcornaz added feature Add a new feature need-usecase This lacks of use-case for now. It has to be motivated by a concrete need before being implemented. labels Feb 26, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
feature Add a new feature need-usecase This lacks of use-case for now. It has to be motivated by a concrete need before being implemented.
Projects
None yet
Development

No branches or pull requests

1 participant