Previous | Next --- Slide 31 of 64
Back to Lecture Thumbnails

Pthreads are expensive because they each require an execution context. It seems like whenever we have a choice about how to implement parallelism, pthreads are the worst option, yet pthreads are the most commonly taught way to parallelize code. Is there any scenario where pthreads are the most appropriate abstraction?


Well, even if you use Cilk, the Cilk runtime is using pthreads to create and manage its thread pool. So for simple parallel structures, you may be paying for pthreads and the something else (Cilk, OpenMP, etc) that you are using.



I guess it's because pthreads gives us (programmers) the greatest control of what's going on -- it gives us experience in actually scheduling work ourselves and play with work assignment, which can be good learning experience.

In practice, I agree that many other libraries are great choices.


Just to add to this. The scenario where pthreads is the most appropriate abstraction is when you have very long-running tasks which are large in size. Like @yimmyz mentioned, they give you the most control over the actual scheduling of the threads.

The classic example is what threads used to be used for: low-latency concurrency. Suppose you have a long-running application that the user can interact with through a GUI, perhaps to cancel the process. For example, this could be a dialog box for a download. One way is to have a single thread that performs the download, and also intermittently checks for the user event. However, this is bad because we need to liter the existing code with these checks, and certain parts of the code might not be amenable to having this check in the middle of them.

A better option is to spawn a separate thread that intermittently runs and checks the state of the GUI to indicate. When it sees a user request, it then communicates it to the other thread, who then can respond appropriately. This is definitely a case where the pthread abstraction fits in nicely. We want a separate execution context for a long-running task that performs very different work than the other thread. Cilk and/or ISPC would not at all be appropriate for this setup.