Producer and Consumer problem
6. Write a multi-threaded program to solve producer and consumer problem.
1 There are two types of worker thread: producer and consumer. A producer thread simply randomly generate an integer between 0-100 (You can use random()/srandom() or drand48()/srand48() to generate random number in C), and put it into the buffer. A consumer thread simple take the first integer from the buffer. A circular array should be used for the buffer. You do not need loop for both types of thread. Each thread only does once and exit.
2 Assume total number of worker thread is 10, and buffer size is also 10. Your program should randomly generate the number of producers and consumers. Their relationship should be : num_producers + num_consumers = num_threads, num_producer - num_consumer <= buffer_size, num_consumer <= num_producer, so that no thread will be blocked forever.
3 Synchronize the producer and consumer.
4 You can choose any type of language (e.g. C/C++/Java) to implement this program. Below is a sample of output. However, the number and the execution order in your program might be different.
Number of producer: 7 Number of consumer: 3
Thread 0 produce 63 in buffer 0, current number of items is 1
Thread 1 consume item 63 in buffer 0, current number of items is 0
Thread 3 produce 45 in buffer 1, current number of items is 1
Thread 4 consume item 45 in buffer 1, current number of items is 0
Thread 5 produce 88 in buffer 2, current number of items is 1
Thread 6 produce 96 in buffer 3, current number of items is 2
Thread 7 produce 26 in buffer 4, current number of items is 3
Thread 8 produce 52 in buffer 5, current number of items is 4
Thread 9 produce 81 in buffer 6, current number of items is 5
Thread 2 consume item 88 in buffer 2, current number of items is 4
There are 4 items left in the buffer: 96,26,52,81