← Back to lessons

47 Monitors

Hard

Monitor is a built-in data structure that binds a mutex to a single related condition variable (wait queue). Monitor can block a thread and wait for a signal from another thread to resume execution. This mechanism uses shared variables to synchronize threads.

Monitor initialization. Condition variable.

Lock the monitor.

Unlock the monitor and wait for notify to continue.

Try to acquire lock.

Change the condition variable.

Notify that condition variable has changed, and maybe other thread can resume its computation.

Wait for the new thread to finish.

monitors.cj
import std.sync.*
import std.time.*

var mon = Monitor()
var flag: Bool = true

main(): Int64 {
    let fut = spawn {
        mon.lock()
        while (flag) {
            println("New thread: before wait")
            mon.wait()
            println("New thread: after wait")
        }
        mon.unlock()
    }

    sleep(10 * Duration.millisecond)

    mon.lock()
    println("Main thread: set flag")
    flag = false
    mon.unlock()

    mon.lock()
    println("Main thread: notify")
    mon.notifyAll()
    mon.unlock()

    fut.get()
    return 0
}

// Output: 
// New thread: before wait
// Main thread: set flag
// Main thread: notify
// New thread: after wait