Page 2 of 2

Re: Thread safety with priorities

Posted: Mon Jun 20, 2016 9:52 am
by mariuszp
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:

Code: Select all

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?

Re: Thread safety with priorities

Posted: Tue Jun 21, 2016 3:46 am
by Combuster
If the thread gets interrupted, it does not sleep, so there's nothing requiring to be woken up in the first place.

Re: Thread safety with priorities

Posted: Tue Jun 21, 2016 11:13 am
by mariuszp
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).

Re: Thread safety with priorities

Posted: Wed Jun 22, 2016 12:38 am
by Combuster
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? :mrgreen:


I know, concurrency can be mindboggling.