|
Meeting Signup |
Projects /
P5Programming homework 5: Threads SynchronizationDue Date: Thursday, May 7 at 9pm You are to do this project BY YOURSELF. This project must be implemented in C. Updates
Goals
OutlineThis is project 6.40 from the book. You will implement a simple producer/consumer style of communication using a bounded buffer. For fun, you get to implement this both with semaphores and condition variables. The buffer you will use is simple: typedef int buffer_item; #define BUFFER_SIZE 5 You will implement two functions: insert and remove buffer_item buffer[BUFFER_SIZE];
int insert_item(buffer_item item) {
/* insert an item into buffer, block until space available */
return 0 if successful, otherwise
return -1 if unsuccessful, such as memory allocation fails
}
int remove_item(buffer_item *item) {
/* remove an item into buffer */
return 0 if successful, otherwise
return -1 if unsuccessful, such as memory allocation fails
}
The main function is simple. It takes three paramters:
The outline of the main function is: int main(int argc, char * argv[]) {
/* 1. get cmd line arguments */.
/* 2. Initialize buffer */
/* 3. Create producer threads */
/* 4. Create consumer threads */
/* 5. Sleep */
/* 6. Exit */
}
The producer and consumer threads are simple: void * producer(void * param) {
buffer_item item;
while (TRUE) {
/* sleep a random time period */
sleep (...);
/* generate a random item */
item = rand();
if (insert_item(item)) == -1) {
fprint(stderr,"Report error condition\n");
} else {
printf("Producer produced %d\n",item);
}
}
}
void * consumer(void * param) {
buffer_item item;
while (TRUE) {
/* sleep a random time period */
sleep (...);
/* generate a random item */
if (remove_item(&item)) == -1) {
fprint(stderr,"Report error condition\n");
} else {
printf("Consumer consumed %d\n",item);
}
}
}
You need to fill in the missing code in the main function and add appropriate synchronization code to the insert/remove item functions. Part 1: SemaphoresImplement the bounded buffer using only sempahores (not semaphores and mutexes). Part 2: Condition variablesImplement this code using mutex locks and condition variables. Part 3: OptionalImplement a pipeline of three stages: an initial producer, a consumer/producer to another buffer, and a final consumer. You may use either semaphores or condition variables. ResourcesCompiling a multi-threaded program with POSIX threads on Linux requires two things. First, you need to include the pthread header file pthread.h in your code. Second, when compiling, you need to link with the pthread library -lpthread . That's about it. What to turn inPlease turn in your source code and a makefile that builds both programs to ~cs537-1/handin/<your login>/p5. |