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

This is not a problem for <strong>Neutrino</strong> — <strong>Neutrino</strong> “limits” you to 32767 threads per<br />

process! However, each thread must have a unique stack. If your stack is a reasonable<br />

size (say 8 KB), you’ll have used 1280 × 8 KB (10 megabytes!) of stack. And for<br />

what? There are only 4 processors in your SMP system. This means that only 4 of the<br />

1280 threads will run at a time — the other 1276 threads are waiting for a CPU. (In<br />

reality, the stack will “fault in,” meaning that the space for it will be allocated only as<br />

required. Nonetheless, it’s a waste — there are still other overheads.)<br />

A much better solution to this would be to break the problem up into 4 pieces (one for<br />

each CPU), and start a thread for each piece:<br />

int num_lines_per_cpu;<br />

int num_cpus;<br />

int<br />

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

{<br />

int cpu;<br />

... // perform initializations<br />

// get the number of CPUs<br />

num_cpus = _syspage_ptr -> num_cpu;<br />

num_lines_per_cpu = num_x_lines / num_cpus;<br />

for (cpu = 0; cpu < num_cpus; cpu++) {<br />

pthread_create (NULL, NULL,<br />

do_one_batch, (void *) cpu);<br />

}<br />

}<br />

... // display results<br />

void *<br />

do_one_batch (void *c)<br />

{<br />

int cpu = (int) c;<br />

int x1;<br />

}<br />

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

do_line_line (x1 + cpu * num_lines_per_cpu);<br />

}<br />

Here we’re starting only num_cpus threads. Each thread will run on one CPU. And<br />

since we have only a small number of threads, we’re not wasting memory <strong>with</strong><br />

unnecessary stacks. Notice how we got the number of CPUs by dereferencing the<br />

“System Page” global variable _syspage_ptr. (For more information about what’s in<br />

the system page, please consult QSS’s Building Embedded <strong>Systems</strong> book or the<br />

include file).<br />

Coding for SMP or single processor<br />

The best part about this code is that it will function just fine on a single-processor<br />

system — you’ll create only one thread, and have it do all the work. The additional<br />

overhead (one stack) is well worth the flexibility of having the software “just work<br />

faster” on an SMP box.<br />

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