COMP 3000 Lab 4 2011: Difference between revisions
Line 11: | Line 11: | ||
==Programs== | ==Programs== | ||
/* race-demo.c */ | /* race-demo.c */ | ||
/* compile with -pthread flag, e.g. | |||
gcc -pthread race-demo.c -o race-demo */ | |||
#include <stdlib.h> | #include <stdlib.h> |
Revision as of 04:44, 24 October 2011
A few guidelines:
- Submit your solutions for both Part A and Part B via WebCT by Friday, Monday, October 28th at 8 PM.
- Please answer using a single text file. Do not submit doc, docx, pdf, or other formats. Also, please do not submit an archive (zip, tarball, rar) of multiple text files, just upload one. (Please don't just cut and paste your work into a text box on webct.)
- Show all your work. Short answers are not sufficient; you should list any websites or individuals you consult and should document any experiments you conducted. For any question that you could just answer without any external reference or experiment, write "(no work required)" after your answer.
- All submitted code should compile and run. Partial code fragments or explanations may not be given credit.
Part A
Part B
Programs
/* race-demo.c */
/* compile with -pthread flag, e.g. gcc -pthread race-demo.c -o race-demo */ #include <stdlib.h> #include <stdio.h> #include <pthread.h> int value; int offset = -1; #define SIZE 10000 #define ROUNDS 100 void *consume_func(void *arg) { int i,r; int *buffer; buffer = (int *) arg; for (r = 1; r <= ROUNDS; r++) { for (i = 0; i < SIZE; i++) { if (buffer[i] < r ) { buffer[i] = -1; } } } return NULL; } void *produce_func( void * arg ) { int i, r, iwon; int *buffer; buffer = (int *) arg; for (r = 1; r <= ROUNDS; r++) { iwon = 1; for( i = 0; i < SIZE; i++ ) { if (buffer[i] == r-1) { buffer[i] = r; } else if ((buffer[i] < r) && (buffer[i] != -1)) { fprintf(stderr, "Huh?! Got value %d\n", (int) buffer[i]); exit(-1); } else if (buffer[i] == -1) { if (iwon) { printf("Consumer got to %d first on round %d.\n", i,r); iwon = 0; } buffer[i] = r; } } if (iwon) { printf("Producer won on round %d!\n",r); } else { printf("Producer lost on round %d.\n",r); } } return NULL; } int main(int argc, char *argv[]) { int *buffer; pthread_t producer_thread, consumer_thread; int r1, r2; buffer = (int *) calloc(SIZE, sizeof(int)); if (buffer == NULL) { fprintf(stderr, "Couldn't allocate memory for buffer!"); exit(-1); } r1 = pthread_create(&producer_thread, NULL, produce_func, buffer); r2 = pthread_create(&consumer_thread, NULL, consume_func, buffer); if (r1 != 0 || r2 != 0) { fprintf(stderr, "Couldn't create threads.\n"); } pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); return 0; }