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 />

Threads in mathematical operations<br />

sharing data, such as a web-server that’s serving multiple clients simultaneously. We’ll<br />

examine these two classes.<br />

Suppose that we have a graphics program that performs ray tracing. Each raster line<br />

on the screen is dependent on the main database (which describes the actual picture<br />

being generated). The key here is this: each raster line is independent of the others.<br />

This immediately causes the problem to stand out as a threadable program.<br />

Here’s the single-threaded version:<br />

int<br />

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

{<br />

int x1;<br />

}<br />

... // perform initializations<br />

for (x1 = 0; x1 < num_x_lines; x1++) {<br />

do_one_line (x1);<br />

}<br />

... // display results<br />

Here we see that the program will iterate x1 over all the raster lines that are to be<br />

calculated.<br />

On an SMP system, this program will use only one of the CPUs. Why? Because we<br />

haven’t told the operating system to do anything in parallel. The operating system isn’t<br />

smart enough to look at the program and say, “Hey, hold on a second! We have 4<br />

CPUs, and it looks like there are independent execution flows here. I’ll run it on all 4<br />

CPUs!”<br />

So, it’s up to the system designer (you) to tell <strong>Neutrino</strong> which parts can be run in<br />

parallel. The easiest way to do that would be:<br />

int<br />

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

{<br />

int x1;<br />

... // perform initializations<br />

for (x1 = 0; x1 < num_x_lines; x1++) {<br />

pthread_create (NULL, NULL, do_one_line, (void *) x1);<br />

}<br />

}<br />

... // display results<br />

There are a number of problems <strong>with</strong> this simplistic approach. First of all (and this is<br />

most minor), the do_one_line() function would have to be modified to take a void *<br />

instead of an int as its argument. This is easily remedied <strong>with</strong> a typecast.<br />

The second problem is a little bit trickier. Let’s say that the screen resolution that you<br />

were computing the picture for was 1280 by 1024. We’d be creating 1280 threads!<br />

April 30, 2009 Chapter 1 • Processes and Threads 43

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

Saved successfully!

Ooh no, something went wrong!