Discussions on more advanced topics such as monolithic vs micro-kernels, transactional memory models, and paging vs segmentation should go here. Use this forum to expand and improve the wiki!
Combuster wrote:Tickets with target threads is as simple as dropping in circular_buffer[ticket_number % buffer_size] = my_thread_id before checking if you have the lock or you have to sleep instead. The exiting thread can remove its thread id slot and wake the next thread if there happens to be one registered.
Just to follow up on that, sleeping-waking code is a caveat. Something as simple as:
if (needs_to_sleep)
{
sleep();
}
(...)
wake_thread_if_sleeping();
Is a race condition, if the wake is performed between the if and the sleep. Instead you can modify wake to prevent the next sleep() call from occurring if the thread is running, or you can do something else/more complicated. It's actually a more fundamental primitive than setting up mutexes.
One question though: what about if we're interrupted after getting the ticket, but before placing our thread ID into the circular_buffer?
How would the unlocking thread then know to wake us up?
If the thread gets interrupted, it does not sleep, so there's nothing requiring to be woken up in the first place.
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
Combuster wrote:If the thread gets interrupted, it does not sleep, so there's nothing requiring to be woken up in the first place.
I meant to ask what happens if it gets woken up before it manages to place its ID in the buffer. But now I realised that this can easily be solved by proper order of operations in the unlock() function (basically, if it hasn't placed its ID in the buffer yet, it means it hasn't checked its ticket yet, and when it does it will see that it's now its turn, so it never goes to sleep).
Of course nobody is going to wake you either when you haven't even told them what your ID is, so why is that suddenly a scenario?
I know, concurrency can be mindboggling.
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]