Skip to content

Instantly share code, notes, and snippets.

@ryohji
Last active October 27, 2019 17:06
Show Gist options
  • Save ryohji/a1f500a391a6216a5006f6fa436335a6 to your computer and use it in GitHub Desktop.
Save ryohji/a1f500a391a6216a5006f6fa436335a6 to your computer and use it in GitHub Desktop.
Producer/Consumer model (without Conditional variable)
val mutex = java.util.concurrent.locks.ReentrantLock()

const val FULL = 2
var que = 0

fun prod() {
    while (true) {
        // P0: lock
        mutex.lock()
        // P1: test
        while (que == FULL) {
            // P4: wait-room
            mutex.unlock()
            // P5: retry
            mutex.lock()
        }
        // P2: produce
        que += 1
        // P3: free
        mutex.unlock()
    }
}

fun cons() {
    while (true) {
        // Q0: lock
        mutex.lock()
        // Q1: test
        while (que == 0) {
            // Q4: wait-message
            mutex.unlock()
            // Q5: retry
            mutex.lock()
        }
        // Q2: consume
        que -= 1
        // Q3: free
        mutex.unlock()
    }
}

This producer/consumer state transition diagram: prod-cons-model

Queue size 1, Producer x 1, Consumer x 1: prod-cons-1 1 1

Queue size 2, Producer x 1, Consumer x 1: prod-cons-2 1 1

Queue size 2, Producer x 2, Consumer x 1: prod-cons-2 2 1

Queue size 2, Producer x 1, Consumer x 2: prod-cons-2 1 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment