The purpose of this lab is to give you practice with threads in C++.
There are two programs for you to work on. The first one won't run so well in Visual Studio so you should run it on uaa-transformer.duckdns.org. All the files are located in ~kjmock/CSCE_A211/lab13
. You can copy the files from that folder into your directory and edit them there.
The first program is here: counter.cpp
It creates 30,000 threads and each thread increments a counter. If the counter starts at 0 then this means that one would expect the final value of the counter to be 30,000. However, if you run it multiple times, then you will see that sometimes the counter value is less than 30,000.
To compile on transformer don't forget that you need to add the -std=c++11
flag and also the -lpthread
flag, e.g: g++ counter.cpp -std=c++11 -lpthread
To do:
The second program is here:
witty.cpp
It reads in this text file which should be in the default directory: witticism.txt
If you compile and run the program it will spit out a witty one liner every 5 seconds. The only way to stop the program is to hit control-c or kill the window. We would like it so if we press a key and enter, then to make the program stop.
To do:Witticism
class in a thread. This means moving or calling the showOneLiners()
function in an operator()()
function, then modify main
so it runs the class in a thread.stop
variable is sent to the thread object in the constructor.
When the stop variable is set, the showOneLiners loop should stop (it will have to wait until
the remainder of the 5 seconds elapses). However, the code will crash because the main
thread will exit before the Witticism thread. Make the main function wait for the thread
to finish by adding the join
function call before your program exits.The program should now quit after typing a key (like 'q') and hitting enter.
Show your working code to the instructor or lab assistant for credit, or email your solution by midnight.