Spawning Your First Threads

If you've never written a program that has created threads before, let's do it now!.

Download the C program located here:

http://15418.courses.cs.cmu.edu/tsinghua2017content/code/threads.cpp

Build the code:

g++ -std=c++11 threads.cpp -o threads

The main function in this code spawns num_threads threads. When a thread is created it immediately begins running code in the thread_run_me() function. This function prints a string five times, like shown below: (the X will be be value of thread_id passed as an input argument to thread_run_me().

Hello 0 from thread X
Hello 1 from thread X
Hello 2 from thread X
Hello 3 from thread X
Hello 4 from thread X

Now run the program.

./threads

You should see a total of 20 lines of output, since each of the num_threads=4 prints "hello" five times. If you take a look at the output, you've notice that the printf output from the different threads is interleaved. This is because if you have a multi-core processor in your computer different cores of the processor will be executing the different simultaneously.

For example, on my computer, the first time I ran the program I received this output: Notice that thread 1 outputs its first "hello" first. In fact, thread 1 outputs its second hello message before thread 2 and thread 3 have even had the opportunity to send their first.

Hello 0 from thread 1
Hello 0 from thread 0
Hello 1 from thread 1
Hello 0 from thread 3
Hello 0 from thread 2
Hello 1 from thread 0
Hello 2 from thread 1
Hello 1 from thread 3
Hello 1 from thread 2
Hello 2 from thread 0
Hello 3 from thread 1
Hello 2 from thread 3
Hello 2 from thread 2
Hello 3 from thread 0
Hello 4 from thread 1
Hello 3 from thread 3
Hello 3 from thread 2
Hello 4 from thread 0
Hello 4 from thread 3
Hello 4 from thread 2

Run the program a few different times and see if you can observe a different order of the printfs on different program executions. For example, I ran the code again and insted got this:

Hello 0 from thread 1
Hello 0 from thread 3
Hello 0 from thread 0
Hello 0 from thread 2
Hello 1 from thread 1
Hello 1 from thread 3
Hello 1 from thread 0
Hello 1 from thread 2
Hello 2 from thread 1
Hello 2 from thread 3
Hello 2 from thread 0
Hello 2 from thread 2
Hello 3 from thread 1
Hello 3 from thread 3
Hello 3 from thread 0
Hello 3 from thread 2
Hello 4 from thread 1
Hello 4 from thread 3
Hello 4 from thread 0
Hello 4 from thread 2

Can you explain why you might see different output from the program each time you run it?