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.

Threads and processes<br />

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

Starting a thread<br />

• When fork() does work <strong>with</strong> multiple threads, you’ll need to register a<br />

pthread_atfork() handler and lock every single mutex before you fork,<br />

complicating the design.<br />

• The child of fork() duplicates all open file descriptors. As we’ll see in the Resource<br />

Manager chapter later, this causes a lot of work — most of which will be<br />

unnecessary if the child then immediately does an exec() and closes all the file<br />

descriptors anyway.<br />

The choice between vfork() and the spawn() family boils down to portability, and what<br />

you want the child and parent to be doing. The vfork() function will pause until the<br />

child calls exec() or exits, whereas the spawn() family of functions can allow both to<br />

run concurrently. The vfork() function, however, is subtly different between operating<br />

systems.<br />

Now that we’ve seen how to start another process, let’s see how to start another thread.<br />

Any thread can create another thread in the same process; there are no restrictions<br />

(short of memory space, of course!). The most common way of doing this is via the<br />

POSIX pthread_create() call:<br />

#include <br />

int<br />

pthread_create (pthread_t *thread,<br />

const pthread_attr_t *attr,<br />

void *(*start_routine) (void *),<br />

void *arg);<br />

The pthread_create() function takes four arguments:<br />

thread<br />

attr<br />

start_routine<br />

arg<br />

a pointer to a pthread_t where the thread ID is stored<br />

an attributes structure<br />

the routine where the thread begins<br />

an argument passed to the thread’s start_routine<br />

Note that the thread pointer and the attributes structure (attr) are optional — you can<br />

pass them as NULL.<br />

The thread parameter can be used to store the thread ID of the newly created thread.<br />

You’ll notice that in the examples below, we’ll pass a NULL, meaning that we don’t<br />

care what the ID is of the newly created thread. If we did care, we could do something<br />

like this:<br />

pthread_t tid;<br />

pthread_create (&tid, ...<br />

printf ("Newly created thread id is %d\n", tid);<br />

36 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!