A C++11 Threads Tutorial

Last week we created a simple program using the pthreads library. This week I’ve “translated” that program into the C++11 threads version, so you can see how it compares.

I say compares, but on linux, using GCC, the C++11 thread library is basically a wrapper for pthreads anyway, so although you are using native C++ commands, they are effectively calling the pthread commands that we saw last week.

So, the first thing to remember, when you are using the new C++11 thread library, is that you have to add a couple of flags to your build in order for it to run properly.

Read moreA C++11 Threads Tutorial

A pthreads Tutorial

I’m going to use a simple program to illustrate the basic use of pthreads, and highlight some of the issues that you may run into when you’re creating your own threaded programs (for C++11 threads, see this post).

I want my program to print a message from each thread I create, to the console, in a different colour.

I’m going to build the program up in three steps, and talk about the issues we encounter on the way. I’m not going to go deeply into the pthreads calls – if you want to read about them in detail, there is an excellent break down and set of tutorials here.

Threads program, version 1 – faulty

Right, so here’s my first version of the program: threads1.cpp. Build it with:

g++ threads1.cpp -lpthread

Take a look, and I’ll talk through what I’ve done below.

Read moreA pthreads Tutorial