How efficient is locking an unlocked mutex? What is the cost of a mutex?

In a low level language (C, C++ or whatever): I have the choice in between either having a bunch of mutexes (like what pthread gives me or whatever the native system library provides) or a single one for an object. How efficient is it to lock a mutex? I.e. how many assembler instructions are there … Read more

Concurrent HashSet in .NET Framework?

I have the following class. class Test{ public HashSet<string> Data = new HashSet<string>(); } I need to change the field “Data” from different threads, so I would like some opinions on my current thread-safe implementation. class Test{ public HashSet<string> Data = new HashSet<string>(); public void Add(string Val){ lock(Data) Data.Add(Val); } public void Remove(string Val){ lock(Data) … Read more

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won’t deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also support recursive mutexes, but if they want to be POSIX conform, they … Read more

Do spurious wakeups in Java actually happen?

Seeing various locking related question and (almost) always finding the ‘loop because of spurious wakeups’ terms1 I wonder, has anyone experienced such kind of a wakeup (assuming a decent hardware/software environment for example)? I know the term ‘spurious’ means no apparent reason but what can be the reasons for such kind of an event? (1 … Read more

Java synchronized method lock on object, or method?

If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method? Example: class X { private int a; private int … Read more