Hello All,

I have a small doubt w.r.t using mutex locks. Say we have a thread-safe function:

int counter;

void foo()
    LOCK_MUTEX(); //  say by pthread_mutex_lock

Now, i understand that this is thread safe because only one thread can "own" a mutex at a time and thus counter is incremented by only one thread at a time. So, if i'm right, it goes something like this:

say thread1 has the mutex, then thread2 is blocked until thread2 releases the mutex. So, when thread2 comes to the LOCK_MUTEX() call, it is blocked and the Operating System unblocks the thread when it knows that the mutex has been released.

1) Is this understanding correct?
2) Does pthread_mutex_lock() make some kernel level calls and interact with the host OS? Could anyone please give a little more details as to how this is done?


Yes, only one thread can run the code when the mutex is acquired. Also remember that in this (very simple) case the counter variable might be cached and different threads could have different values. volatile might be useful.

On the internals of pthread implementation it depends on the platform. On Windows it uses Critical Sections which use part user space and part kernel space code.

Thanks for the reply Symbiatch

Also remember that in this (very simple) case the counter variable might be cached

Could you please explain what you meant by that? Are there multiple instances of the global variables?

The value could be held in a processor register, so even though there is only one variable in memory, the code could not even read it from the memory since it thinks it's already available in a register. If another CPU changes the value during that time, the CPUs might see a different value.

Using volatile keyword forces the value to be read from the memory every time and the compiler won't optimize its usage.

This question has already been answered. Start a new discussion instead.