Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KJTsanaktsidis/ddfbccc7b48d90277ec81ebf16591cb8 to your computer and use it in GitHub Desktop.
Save KJTsanaktsidis/ddfbccc7b48d90277ec81ebf16591cb8 to your computer and use it in GitHub Desktop.
Thread 1 locks the mutex
Thread 1 can get the resource
Thread 1 sleeps for a while ("sleep with resource #1")
Thread 2 tries to lock the mutex, gets put on the waitq
Thread 3 tries to lock the mutex, now the waitq is [2, 3]
Thread 1 returns the resource and unlocks the mutex
Thread 1 signals thread 2, since it's first on the waitq
Thread 2 is eligible for running now (according to ruby) but it's blocked waiting for the GVL
Thread 1 locks the mutex again
Thread 1 takes the resource again
Thread 1 sleeps for a while ("sleep with resource #2")
Since thread 1 is sleeping, Thread 2 can now acquire the GVL and run
Thread 2 finds the resource is taken, so it goes back to sleep. It gets added to the back of the mutex's waitq, so the waitq is [3, 2]
Thread 1 finishes sleeping
Thread 1 releases the mutex and signals the condition variable again. Thread 3 is signaled, since it's at the front of the waitq. The waitq is now [2].
Thread 3 is elligible to run now, but it's blocked waiting for the GVL
Thread 1 does "sleep wihtout resource"
Thread 3 can get the GVL now, so it runs
Thread 3 locks the mutex
Thread 3 can get the resource
Thread 3 sleeps for a while ("sleep with resource #1")
Thread 1 finishes its "sleep without resource" and wakes up. it tries to get the mutex, but can't (thread 3 has it). So, it gets added to the back of the waitq. The waitq is now [2, 1].
Thread 3 returns the resource and unlocks the mutex.
Thread 3 signals thread 2, since it's first on the waitq. The waitq is now [1].
Thread 2 is eligible for running now (according to ruby) but it's blocked waiting for the GVL
Thread 3 locks the mutex again
Thread 3 takes the resource again
Thread 3 sleeps for a while ("sleep with resource #2")
Since thread 3 is lseeping, Thread 2 can now acquire the GVL and run
Thread 2 finds the resource is taken, so it goes back to sleep. It gets added to the back of the mutex's waitq, so the waitq is [1, 2].
Thread 3 finishes sleeping. & returns the resource
Thread 3 releases the mutex and signals the condition variable again. Thread 1 is signaled, since it's at the front of the waitq. The waitq is now [2].
Thread 1 is eligible to run now, but it's blocked waiting for the GVL.
Thresd 3 does "sleep without resource")
Thread 1 can get the GVL now, so it runs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment