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. Threads and processes<br />

This is exactly what happened <strong>with</strong> the graphics example. The main thread needs to<br />

wait until all the worker threads have completed, and only then can the next part of the<br />

program begin.<br />

Note an important distinction, however. With pthread_join(), we’re waiting for the<br />

termination of the threads. This means that the threads are no longer <strong>with</strong> us; they’ve<br />

exited.<br />

With the barrier, we’re waiting for a certain number of threads to rendezvous at the<br />

barrier. Then, when the requisite number are present, we unblock all of them. (Note<br />

that the threads continue to run.)<br />

You first create a barrier <strong>with</strong> pthread_barrier_init():<br />

#include <br />

int<br />

pthread_barrier_init (pthread_barrier_t *barrier,<br />

const pthread_barrierattr_t *attr,<br />

unsigned int count);<br />

This creates a barrier object at the passed address (pointer to the barrier object is in<br />

barrier), <strong>with</strong> the attributes as specified by attr (we’ll just use NULL to get the<br />

defaults). The number of threads that must call pthread_barrier_wait() is passed in<br />

count.<br />

Once the barrier is created, we then want each of the threads to call<br />

pthread_barrier_wait() to indicate that it has completed:<br />

#include <br />

int<br />

pthread_barrier_wait (pthread_barrier_t *barrier);<br />

When a thread calls pthread_barrier_wait(), it will block until the number of threads<br />

specified initially in the pthread_barrier_init() have called pthread_barrier_wait()<br />

(and blocked too). When the correct number of threads have called<br />

pthread_barrier_wait(), all those threads will “simultaneously” unblock.<br />

Here’s an example:<br />

/*<br />

* barrier1.c<br />

*/<br />

#include <br />

#include <br />

#include <br />

#include <br />

pthread_barrier_t<br />

barrier; // the barrier synchronization object<br />

void *<br />

thread1 (void *not_used)<br />

{<br />

time_t now;<br />

char buf [27];<br />

April 30, 2009 Chapter 1 • Processes and Threads 47

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

Saved successfully!

Ooh no, something went wrong!