/* * Each thread executes this process until completed */ void mythread(int thread_id) { int n, i, j; if(thread_id < 4){ n = 10; } else { n = 15; } if(thread_id % 2 == 0){ //Consumer for (i = 0; i < n; i++){ mysem_wait(full); mysem_wait(mutex); buffer_count--; buffer[buffer_count] = ' '; printf("Thread %d consumed item #%d. Buffer count = %d\n", thread_id, i, buffer_count); mysem_signal(mutex); mysem_signal(empty); for (j = 0; j < MAX/2; j++); } } else { //Producer for (i = 0; i < n; i++){ mysem_wait(empty); mysem_wait(mutex); buffer[buffer_count] = 'X'; buffer_count++; printf("Thread %d produced item #%d. Buffer count = %d\n", thread_id, i, buffer_count); mysem_signal(mutex); mysem_signal(full); for (j = 0; j < MAX/2; j++); } } }
// Provided thread code void consumer(int thread_id) { // The declaration of j as an integer was added on 10/24/2011 int i, j, n; n = (thread_id < 4)? 10: 15; for (i = 0; i < n; i++) { // Wait on full mysem_wait(full); // Wait on mutex mysem_wait(mutex); // modify the buffer removeX(); // Release mutex, up empty mysem_signal(mutex); mysem_signal(empty); for (j = 0; j < MAX; j++); } }
// Provided thread code void producer(int thread_id) { // The declaration of j as an integer was added on 10/24/2011 // The threads with ID#(0 - 3) perform insertion/deletion operations for 10 times // while other threads perform the operations for 15 times int i, j, n; n = (thread_id < 4)? 10: 15; for (i = 0; i < n; i++) { // Wait on empty mysem_wait(empty); // Wait on mutex mysem_wait(mutex); // modify the buffer addX(); // Release stuff, up full mysem_signal(mutex); mysem_signal(full); for (j = 0; j < MAX; j++); } }