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:
Queue size 1, Producer x 1, Consumer x 1:
Queue size 2, Producer x 1, Consumer x 1: