Write a program that will take a list of filenames on the command-line. If the list is empty, print an error message to stderr and exit. The goal is to compute how many lines are in each file using a Posix thread for each file.
Create a Posix thread for each argument given on the command-line. Each thread should open its filename. If the open fails, the thread should print an error message to stderr and terminate. If the open succeeds, the thread should read the file using getc and count the number of newlines. When EOF is reached, the thread should print to stdout its filename with the number of newlines in the file, and terminate the message with a newline. The thead can then exit.
For full credit, also have your threads coordinate to have each created thread add its newline count to a global sum. (If a thread had a bad filename, have it contribute zero to the global sum.) And then have the main thread print the final global sum to stdout. Use a mutex to control the update to the global sum.
When compiling programs that use Posix threads, you must provide the -pthread flag.
Check the return value from each POSIX thread function to be sure that the call succeeded.
You should submit all the source code for your assignment
in one file called lab7.c
.
80 points will be awarded for having the threads count and print the number of newlines in their files. 20 points will be awarded for having the threads coordinate to generate a global count of the newlines.
You can test your program using the files in the directory
~cs520/public/books
.
Run your program using the
valgrind helgrind
facility to check for threading errors:
valgrind --tool=helgrind lab7
.
(This assumes the executable for your program is called "lab7".)
Try having the threads update a global sum without a mutex to see what
helgrind will say about that.
% ~cs520/bin/submit lab7 lab7.c
Submissions can be checked by typing:
% ~cs520/bin/scheck lab7
Remember that there are no late submissions of labs. Submit what you have prior to noon on Sunday March 26.
Comments and questions should be directed to pjh@cs.unh.edu