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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

Okay, great. Now what about the “WAIT” call? As we suggested earlier, it’s<br />

effectively the pthread_sleepon_wait() call. Here’s the second while loop:<br />

while (!data_ready) {<br />

pthread_sleepon_wait (&data_ready);<br />

}<br />

The pthread_sleepon_wait() actually does three distinct steps!<br />

1 Unlock the sleepon library mutex.<br />

2 Perform the waiting operation.<br />

3 Re-lock the sleepon library mutex.<br />

The reason it has to unlock and lock the sleepon library’s mutex is simple — since the<br />

whole idea of the mutex is to ensure mutual exclusion to the data_ready variable, this<br />

means that we want to lock out the producer from touching the data_ready variable<br />

while we’re testing it. But, if we don’t do the unlock part of the operation, the<br />

producer would never be able to set it to tell us that data is indeed available! The<br />

re-lock operation is done purely as a convenience; this way the user of the<br />

pthread_sleepon_wait() doesn’t have to worry about the state of the lock when it<br />

wakes up.<br />

Let’s switch over to the producer side and see how it uses the sleepon library. Here’s<br />

the full implementation:<br />

producer ()<br />

{<br />

while (1) {<br />

// wait for interrupt from hardware here...<br />

pthread_sleepon_lock ();<br />

data_ready = 1;<br />

pthread_sleepon_signal (&data_ready);<br />

pthread_sleepon_unlock ();<br />

}<br />

}<br />

As you can see, the producer locks the mutex as well so that it can have exclusive<br />

access to the data_ready variable in order to set it.<br />

It’s not the act of writing a 1 to data_ready that awakens the client! It’s the call to<br />

pthread_sleepon_signal() that does it.<br />

Let’s examine in detail what happens. We’ve identified the consumer and producer<br />

states as:<br />

April 30, 2009 Chapter 1 • Processes and Threads 61

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

Saved successfully!

Ooh no, something went wrong!