Mutex
This lesson discusses Mutex as used in Ruby.
We'll cover the following...
Mutex
Mutex
is the most basic or primitive synchronization construct available in Ruby. It offers two methods: lock()
and unlock()
. A Mutex
object can only be unlocked by a thread that locked it in the first place. Consider the snippet below, where the child and the main thread alternatively acquire the mutex. The main thread blocks for the period the child holds the mutex.
Press + to interact
require 'date'# Create a Mutex objectmutex = Mutex.new# Spawn a child threadThread.new doputs("Child thread acquiring mutex")mutex.lock()sleep(3)puts("Child thread releasing mutex")mutex.unlock()end# Sleep main thread to give child thread a# chance to acquire the mutex firstsleep(1)puts("Main thread attempting to acquire mutex")mutex.lock()puts("Main thread acquires mutex")mutex.unlock()
As mentioned in the ...