.. _Extended6Primes:
.. raw:: html
.. |--| unicode:: U+2013 .. en dash
.. |---| unicode:: U+2014 .. em dash, trimming surrounding whitespace
:trim:
.. This file is part of the OpenCSF eTextbook project. It was
.. auto-generated by scripts from the OpenDSA eTextbook project.
.. See https://OpenCSF.org for more details. OpenCSF is distributed
.. under a Creative Commons Attribution-NonCommercial 4.0 International
.. License (see http://creativecommons.org/licenses/by-nc/4.0/),
.. Copyright (c) 2019-2021 by Michael S. Kirkpatrick. OpenDSA is
.. distributed under an MIT open source license, Copyright (c) 2012-2021
.. by the OpenDSA Project Contributors.
.. avmetadata::
:author: Michael S. Kirkpatrick
:requires:
:satisfies:
:topic:
Extended Example: Concurrent Prime Number Search
================================================
This second example shows a different style of multithreaded programming.
Instead of assigning a unique task to a particular thread, this example creates
multiple threads that all execute the same code, but on different input
parameters. For systems with :term:`multiprocessing` capabilities, this style of
programming forms the foundation of parallel execution. Since each thread's
calculations are independent of all the others' calculations, they can run in
parallel and compute the same answers.
.. codeinclude:: Threads/ExtEx-6-2.c
:linenos: true
The time command-line utility can be used to measure the amount of time it takes
to run a program. However, time gives you multiple pieces of information to
interpret. The *real* time is how much total time elapsed on the system clock
from the start to finish. The *user* time is how much total CPU time was spent
on all of the processors combined. For instance, if a program runs in perfect
parallelism on 2 cores for 15 minutes, the real time would be 15 minutes, but
the user time would be 30 minutes.
The following output shows the results for running the prime number program
above twice. The first set of results (approximately 7.5 minutes for both real
and user time) used only a single thread. The second set used 4 threads (best
choice for the quad-core system used).
.. codeinclude:: Threads/Timing.txt
First, note that the parallel version took more total CPU time (almost 10
minutes); this kind of overhead is typical, as there are overhead performance
penalties for using multiple threads. Second, the real time was only about 1/3
of the user time, not 1/4. In practice, no system ever achieves perfect parallel
execution. Chapter 9 will explain the limits of parallelism in more detail.