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
     ++counter;    
    UNLOCK_MUTEX();
}

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.

Questions:
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?

Thanks!

Member Avatar for Symbiatch

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?

Member Avatar for Symbiatch

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.

got it, thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.