我希望这能帮助你。
生产者和消费者线程问题。
#include <stdio.h>
#include <pthread.h>
#define MAX 10000000000
//#define MAX 10
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int maxbuf=5 ; // max produce count.
int buffer = 0;
void* producer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
pthread_mutex_lock(&the_mutex); /* protect buffer */
printf("produce:get lock\n") ;
if(buffer==maxbuf) {
printf("produce:wait! maxbuffer.\n") ;
pthread_cond_wait(&condp, &the_mutex);
printf("produce:wake--\n") ;
}
buffer++;
printf("produce: buffer=%d\n", buffer) ;
pthread_cond_signal(&condc); /* wake up consumer */
pthread_mutex_unlock(&the_mutex);
usleep(rand()%100);
}
pthread_exit(0);
}
void* consumer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
pthread_mutex_lock(&the_mutex);
printf("consume:get lock\n") ;
if (buffer == 0) /* If there is nothing in the buffer then wait */
{
printf("consume: wait! empty.\n") ;
pthread_cond_wait(&condc, &the_mutex);
printf("consume: wake--.\n") ;
}
buffer--;
printf("consume: buffer=%d\n", buffer) ;
pthread_cond_signal(&condp); /* wake up producer */
pthread_mutex_unlock(&the_mutex);
usleep(rand()%100);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t pro, con;
// Initialize the mutex and condition variables
/* What's the NULL for ??? */
pthread_mutex_init(&the_mutex, NULL);
pthread_cond_init(&condc, NULL); /* Initialize consumer condition variable */
pthread_cond_init(&condp, NULL); /* Initialize producer condition variable */
// Create the threads
pthread_create(&con, NULL, consumer, NULL);
pthread_create(&pro, NULL, producer, NULL);
// Wait for the threads to finish
// Otherwise main might run to the end
// and kill the entire process when it exits.
pthread_join(con, NULL);
pthread_join(pro, NULL);
// Cleanup -- would happen automatically at end of program
pthread_mutex_destroy(&the_mutex); /* Free up the_mutex */
pthread_cond_destroy(&condc); /* Free up consumer condition variable */
pthread_cond_destroy(&condp); /* Free up producer condition variable */
}
输出如下。。。
双螺纹座圈。
consume:get lock
consume: buffer=2
produce:get lock
produce: buffer=3
produce:get lock
produce: buffer=4
consume:get lock
consume: buffer=3
consume:get lock
consume: buffer=2
produce:get lock
如果为空
produce:get lock
produce: buffer=1
consume:get lock
consume: buffer=0
consume:get lock
consume: wait! empty.
produce:get lock
produce: buffer=1
consume: wake--.
consume: buffer=0
produce:get lock
produce: buffer=1
consume:get lock
如果最大产量。
produce:get lock
produce: buffer=5
consume:get lock
consume: buffer=4
produce:get lock
produce: buffer=5
produce:get lock
produce:wait! maxbuffer.
consume:get lock
consume: buffer=4
produce:wake--
produce: buffer=5
produce:get lock