Does a synchronization yield on waiting thread?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 12 20:07:05 PDT 2015


On 9/12/15 10:48 PM, Prudence wrote:
> It would seem to be the logical thing to do?
>
> That is, suppose two threads are sharing a resource. Thread A has it
> locked. B is "waiting". Is B in a loop burning cycles running in the
> background(regardless of thread.sleep, which only alleviates the
> problem) or does it yield completely and somehow inform the lock to
> resume it when A has unlocked the resources?

If you are using D mutexes or synchronized statements, it uses the OS' 
mechanisms (e.g. pthreads). For all supported OSes, this means it is 
asleep and waiting for the OS to awaken it when it has locked the resource.

> The first one burns cycles and can have timing problems. I.e., What if A
> locks and unlocks at the same rate that B checks? (I suppose a random
> sleep time would help with this) (

You don't have to worry about this. If A unlocks a resource that B is 
waiting for the lock, it cannot lock it again before B gets it.

-Steve


More information about the Digitalmars-d-learn mailing list