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.

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

Synchronizing to the termination of a thread<br />

I mentioned that there were a number of problems <strong>with</strong> the simplistic code sample<br />

initially shown. Another problem <strong>with</strong> it is that main() starts up a bunch of threads and<br />

then displays the results. How does the function know when it’s safe to display the<br />

results?<br />

To have the main() function poll for completion would defeat the purpose of a realtime<br />

operating system:<br />

int<br />

main (int argc, char **argv)<br />

{<br />

...<br />

// start threads as before<br />

}<br />

while (num_lines_completed < num_x_lines) {<br />

sleep (1);<br />

}<br />

Don’t even consider writing code like this!<br />

There are two elegant solutions to this problem: pthread_join() and<br />

pthread_barrier_wait().<br />

Joining<br />

The simplest method of synchronization is to join the threads as they terminate.<br />

Joining really means waiting for termination.<br />

Joining is accomplished by one thread waiting for the termination of another thread.<br />

The waiting thread calls pthread_join():<br />

#include <br />

int<br />

pthread_join (pthread_t thread, void **value_ptr);<br />

To use pthread_join(), you pass it the thread ID of the thread that you wish to join, and<br />

an optional value_ptr, which can be used to store the termination return value from the<br />

joined thread. (You can pass in a NULL if you aren’t interested in this value — we’re<br />

not, in this case.)<br />

Where did the thread ID came from? We ignored it in the pthread_create() —we<br />

passed in a NULL for the first parameter. Let’s now correct our code:<br />

int num_lines_per_cpu, num_cpus;<br />

int main (int argc, char **argv)<br />

{<br />

int cpu;<br />

pthread_t *thread_ids;<br />

... // perform initializations<br />

thread_ids = malloc (sizeof (pthread_t) * num_cpus);<br />

April 30, 2009 Chapter 1 • Processes and Threads 45

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

Saved successfully!

Ooh no, something went wrong!