26.02.2014 Views

Getting Started with QNX Neutrino - QNX Software Systems

Getting Started with QNX Neutrino - QNX Software Systems

Getting Started with QNX Neutrino - QNX Software Systems

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

More on synchronization<br />

© 2009, <strong>QNX</strong> <strong>Software</strong> <strong>Systems</strong> GmbH & Co. KG.<br />

Sleepons versus condvars<br />

#include <br />

#include <br />

pthread_mutex_t mutex_xy = PTHREAD_MUTEX_INITIALIZER;<br />

pthread_cond_t cv_xy = PTHREAD_COND_INITIALIZER;<br />

int x, y;<br />

int isprime (int);<br />

thread1 ()<br />

{<br />

for (;;) {<br />

pthread_mutex_lock (&mutex_xy);<br />

while ((x > 7) && (y != 15)) {<br />

pthread_cond_wait (&cv_xy, &mutex_xy);<br />

}<br />

// do something<br />

pthread_mutex_unlock (&mutex_xy);<br />

}<br />

}<br />

thread2 ()<br />

{<br />

for (;;) {<br />

pthread_mutex_lock (&mutex_xy);<br />

while (!isprime (x)) {<br />

pthread_cond_wait (&cv_xy, &mutex_xy);<br />

}<br />

// do something<br />

pthread_mutex_unlock (&mutex_xy);<br />

}<br />

}<br />

thread3 ()<br />

{<br />

for (;;) {<br />

pthread_mutex_lock (&mutex_xy);<br />

while (x != y) {<br />

pthread_cond_wait (&cv_xy, &mutex_xy);<br />

}<br />

// do something<br />

pthread_mutex_unlock (&mutex_xy);<br />

}<br />

}<br />

In these cases, waking up one thread isn’t going to cut it! We must wake up all three<br />

threads and have each of them check to see if its predicate has been satisfied or not.<br />

This nicely reflects the second case in our question above (“Why are these threads<br />

waiting?”). Since the threads are all waiting on different conditions (thread1() is<br />

waiting for x to be less than or equal to 7 or y to be 15, thread2() is waiting for x to be a<br />

prime number, and thread3() is waiting for x to be equal to y), we have no choice but<br />

to wake them all.<br />

Sleepons have one principal advantage over condvars. Suppose that you want to<br />

synchronize many objects. With condvars, you’d typically associate one condvar per<br />

object. Therefore, if you had M objects, you’d most likely have M condvars. With<br />

66 Chapter 1 • Processes and Threads April 30, 2009

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!