Jay Taylor's notes
back to listing indexCondition Variable and Measure the Speed of Context Switching
[web search]Yi Wang's Tech Notes
A blog ported from http://cxwangyi.blogspot.com
The pthread tutorial https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview gives a concise but clear description about condition variable:
- While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data.
- A condition variable is always used in conjunction with a mutex lock.
And a representative sequence for using condition variables is shown below.
Two important points from above illustration:
- pthread_cond_wait unlocks the mutex so another thread can have the chance to signal the condition variable.
- When signaled, pthread_cond_wait locks the mutex. (If the mutex is locked by another thread, pthread_cond_wait has to wait for the mutex before returning.)
To better understand condition variable, let us take a look at the answer to a Google interview question: how to measure the speed of context switch. The answer was given in:
http://forum.codecall.net/c-c/31589-c-program-measures-speed-context-switch-unix-linux.html
Ah, UNIX stuff. Essentially you would create a function to alternate between persistant thread states, set lock and start/wakeup/sleep conditions plus a counter.
Next we create persistant threads t1 and t2 which are unlocked (awoken), and we roughly sleep one second to let them do their firing. (rough approximate of one second, granularity is different among platforms/clocks)
Related
POSIX Thread and Semaphore on Darwin and CygwinWith 5 comments
Why Go? Use Racket!In "C++"
Follow “Yi Wang's Tech Notes”
Get every new post delivered to your Inbox.
Join 40 other followers