POSIX Threads: State Variables - What's the Use?

I recently worked with pthreads in a fair battle, and there’s one little thing that I still don’t quite understand. I know that condition variables are designed to wait for a certain condition to be met (or "signaled"). My question is: how is this any different from regular mutexes?

From what I understand, only a mutex with additional logic to unlock another mutex (and lock it again) are not condition variables when the condition becomes true?

Pseudodecode example:

mutex mymutex; condvar mycond; int somevalue = 0; onethread() { lock(mymutex); while(somevalue == 0) cond_wait(mycond, mymutex); if(somevalue == 0xdeadbeef) some_func() unlock(mymutex); } otherthread() { lock(mymutex); somevalue = 0xdeadbeef; cond_signal(mycond); unlock(mymutex); } 

So cond_wait in this example unlocks mymutex and then expects mycond be.

If so, aren't only mutexes with extra magic condition variables? Or am I misunderstanding the fundamentals of mutexes and variable conditions?

+4
source share
3 answers

The simple answer is that you can wake up more than one thread from condition variables, but a mutex allows only one thread to execute a protected block.

+2
source

They are not exactly mutexes with extra magic, although in some abstractions (monitoring is used as java and C #), the condition variable and the mutex are combined into one block. The purpose of the condition variables is to avoid waiting / polling in standby mode and hinting at the runtime, which should be scheduled "next." Think about how you could write this example without condition variables.

 while(1) { lock(mymutex) if( somevalue != 0) break; unlock(mymutex); } if( somevalue == 0xdeadbeef ) myfunc(); 

You will sit in a tight loop in this thread, burning a lot of processor and making a lot of debate about locking. If locking / unlocking a mutex is cheap enough, you may find yourself in a situation where otherthread never has the ability to get a lock (although real-world mutexes usually distinguish between thread ownership and lock presence, and also have fairness concepts, so this is unlikely to actually happen) .

You can reduce the wait by inserting a dream,

 while(1) { lock(mymutex) if( somevalue != 0) break; unlock(mymutex); sleep(1); // let some other thread do work } 

but how long is a good time to sleep? Basically you are just wondering. Runtime also cannot understand why you are sleeping, or what you are waiting for. The condition variable allows the runtime to at least to some extent know which threads are currently interested in the same event.

+12
source

The two structures are completely different. Mutex is designed to provide serialized access to some resource. The condition variable is designed so that one thread can notify some other thread that some event has occurred.

+11
source

All Articles