This is a continuation of Concurrency, day 1.
Goals for today
- See a naturally threaded program (worker thread + progress-bar thread + input thread).
- Get to know a
producer-consumer
implementation using
busy waiting.
- Compare the busy-waiting producer-consumer to a blocking producer-consumer using
semaphores.
Samples
- progress-bar.c: this demonstrates one good
reason to thread a program. Here, we have three threads. One does the work (counting
prime numbers), one produces a progress bar to keep the user informed, and one
waits for the user to type X to cancel the program. Take a look at each thread's code: how
complicated are the threads? How would you achieve the same effect without threads?
How complicated would that code be?
- producer-consumer-busy-waiting.c: this
is an implementation of the program described at the end of
Concurrency day 1. Run it in one window and run
top. (Once top is running, type "o" and then "cpu" to sort the processes
by CPU usage.) What percentage of processor time is the producer/consumer program using?
producer-consumer-blocking-macos.c: same thing,
but using semaphores
to put the producer to sleep when the buffer is full and put the consumer to sleep
when the buffer is empty. (Note that this sample uses the semaphores available on macOS. You
would use pthreads semaphores
on Linux or other non-Mac Unix systems.)
How does the CPU usage of this program compare to that of the busy-waiting version?
OK, that wasn't very satisfying. But try this: run the busy-waiting version for 10 seconds
then hit Ctrl-C. Then do the same thing for the blocking version. See anything different?
What next?
For this whirlwind intro to concurrency, perhaps the best use of your time is to study the
samples a little more, and play around with them to see what happens when you make changes.
That said, here are a few quick ideas for further study.
- Read about deadlock. How might you
modify one of our sample programs to intentionally cause deadlock? (e.g. What if everybody
locks the lock, but nobody unlocks it?)
- Figure out how to do threaded programs in Java and/or Python, and how to avoid race conditions.
- Read up on synchronization,
and ways in which threads could be controlled to execute in specific orders.
- Take an Operating Systems course...