#include #include #include #include using namespace std; // prototype for thread routine void *print_message_function1 ( void *ptr ); void *print_message_function2 ( void *ptr ); // struct to hold data to be passed to a thread: now it has a mutex pointer typedef struct str_thdata { int thread_no; int shared_buf[1000]; int buf_size; pthread_mutex_t *mutex; } thdata; int main() { pthread_t thread1, thread2; thdata data; // mutex pthread_mutex_t mutex; pthread_mutex_init(&mutex, NULL); // initialize data to pass to thread 1 data.thread_no = 1; data.buf_size = 0; data.mutex = &mutex; // create threads 1 and 2 pthread_create (&thread1, NULL, print_message_function1, (void *) &data); pthread_create (&thread2, NULL, print_message_function2, (void *) &data); pthread_join(thread1, NULL); pthread_join(thread2, NULL); exit(0); } void *print_message_function1 ( void *ptr ) { thdata *data; data = (thdata *) ptr; // type cast to a pointer to thdata pthread_mutex_t *mutex = data->mutex; int i; int cnt = 0; while (cnt < 999) { for (i=cnt;ithread_no, "Hello", i); data->shared_buf[i]=i; data->buf_size += 1; pthread_mutex_unlock (mutex); } cnt += 50; } pthread_exit(0); } void *print_message_function2 ( void *ptr ) { thdata *data; data = (thdata *) ptr; // type cast to a pointer to thdata int cnt = 0; int k; pthread_mutex_t *mutex = data->mutex; while (cnt < 999) { if (data->buf_size >= 100) { pthread_mutex_lock (mutex); printf ("buf_size: %d \n", data->buf_size); for (k=cnt;kthread_no, "Hi", k, data->shared_buf[k]); } data->buf_size -= 100; cnt += 100; pthread_mutex_unlock (mutex); } } pthread_exit(0); }