Right click and download this link. This is the skeleton of your lab.
What it will do
A common use for multiple threads is to do something that takes a long time on a second thread, so that the main thread can continue working.
This program supports 3 commands:
exit- exits the main thread.
status- shows how many alarm threads are pending.
alarm n- sets an alarm for
nseconds from now.
- when the alarm goes off, it prints a message.
This seems like a silly program, but the way it works is exactly how more complex programs work. Once you learn this pattern, you can apply it to many other kinds of problems, like:
- doing complicated calculations in the background
- downloading files in the background
- periodically reminding the user of something
- pretty much any long-running task in a GUI application
Here is an example interaction with the program:
$ ./lab8 > status 0 alarm(s) pending. > alarm 5 > alarm 8 > status 2 alarm(s) pending. > (RING RING!) status 1 alarm(s) pending. > sta(RING RING!)tus 0 alarm(s) pending. > alarm 3 > exit still 1 alarm(s) pending... (RING RING!) $
Above, you can see it act kind of funny… the
(RING RING!) are the alarms going off. Sometimes, they go off in the middle of the user typing something. Yep! That’s the point! :D
What to do
Compile it like so:
gcc -lpthread -Wall -Werror --std=c99 -o lab8 lab8.c
Don’t forget the
-lpthread gcc flag!
If you compile and run it right now, it won’t do much. The functions you have to implement are at the bottom. See below for details.
- Refer to the threading examples I gave in class on the examples page, particularly
- Some of the functions really are “that easy” and only take a couple lines of code.
- If you are only reading a shared global variable, technically you don’t have to lock its mutex…
- You can print out the
\aescape character to make your console go “ding” :)
Don’t do everything at once. Implement and test each function below in the order given.
exit_main_thread()- for the
- If there are any threads running, it should say how many there are left.
- Then you can safely exit the main thread with
pthread_exit(). Look it up!
- When you use this, the other threads will keep running.
- If there are no other threads running, then this behaves like normal
show_status()- for the
- This should show how many alarm threads are running.
- I gave you the
num_threadsvariable to count them.
- Read the comment.
- This should properly lock/unlock the mutex around its code.
22_thread_cooperating.cin the examples.
set_alarm(long duration)- for the
- Read the comments.
- Write a new function to serve as the thread’s main function.
21_thread_test.cto see how we “sneak” an integer into the thread’s main function.
- The thread’s main function should:
- print a message
fflush(stdout)after printing, if you don’t use
- decrement the number of threads using
Please remove all the comments I put in the file before you submit.
Then submit as usual.