Be sure you have read Chapter 2, sections 2.1 through 2.3.
Answer the following questions. You may write out your answers by hand or using a word processor or other program, but please submit hard copy, either in class or in my mailbox in the department office.
Do the following programming problems. You will end up with at least one code file per problem. Submit your program source (and any other needed files) by sending mail to bmassing@cs.trinity.edu, with each file as an attachment. Please use a subject line that mentions the course number and the assignment (e.g., ``csci 3323 homework 2''). You can develop your programs on any system that provides the needed functionality, but I will test them on one of the department's Linux machines, so you should probably make sure they work in that environment before turning them in.
Start by compiling the program, running it, and observing its behavior. To compile with gcc, you will need the extra flag -pthread and also -std=c99, e.g.,
gcc -Wall -std=c99 -pthread m-e-problem.c(Or download this Makefile and type make m-e-problem.) The program requires several command-line arguments, described in comments at the top of the code. (If you have trouble remembering the order, notice that the program prints a meant-to-be-helpful usage message if run with no arguments.)
You are to produce two corrected versions of this program:
NOTE about shared variables: Optimizing compilers play a lot of tricks to reduce actual accesses to memory, as do most processors. What this means for multithreaded programs is that it is very difficult to guarantee that changes made to a shared variable in one thread are visible to other threads. Declaring shared variables volatile avoids at least some compile-time optimizations but does not provide any guarantees about what will happen at runtime, especially if there are multiple processors. For the latter, what is needed is a ``memory fence'', i.e., a way of specifying that at a particular point in the program all memory reads and writes have completed. As far as I know there is no portable way to achieve this in C99; one must fall back on compiler- or processor-specific code. The starter code includes a function memory_fence that invokes a gcc-specific function providing a memory fence and recommends its use in the functions to begin and end the critical region. (Disclaimer: Apparently the version of this function present on our classroom/lab machines does nothing! This may be a bug in gcc. My sample solutions seem to work correctly anyway.) Note that some library functions for synchronization (e.g., the ones included with POSIX threads) incorporate this functionality as well.