首页 > 试题广场 >

The code below is an example p

[填空题]

The code below is an example program of producer-consumer. The product produce numbers from 1 to MAX and the consumer will read it. Please fill blanks in the code

#include <stdio.h>

#include <pthread.h>

#define MAX 1000000000    /* how many numbers to produce */

pthread_mutex_t  the_mutex;

pthread_cond_t  condc, condp;

int buffer = 0;         /* buffer used between producer and consumer*/

void *producer(void *ptr) /*produce data*/

{

int i;

for (i=1; i<=MaX; i++)   {

pthread_mutex_lock(&the_mutex);

while ( 1 )

pthread_cond_wait (&condp, &the_mutex);

buffer = i;

2

3

}

pthread_exit (0);

}

void *consumer (void *ptr)  /*consume data*/

{

int i, res;

for (i = 1; i<=MAX; i++)   {

pthread_mutex_lock (&the_mutex);

while ( 4 )

pthread_cond_wait  ( 5 , &the_mutex);

res = buffer;

buffer = 0;

pthread_cond_signal(&condp);

6
printf(“buffer=%d\n” , res);

}

pthread_exit (0);

}

int main (int argc, char **argv)
{

pthread_t pro,con;

pthread_mutex_init (&the_mutex, 0);

pthread_cond_init (&condc, 0);

pthread_cond_init (&condp, 0);

pthread_create (&con, 0, consumer, 0);
pthread_create (&pro, 0, producer, 0);

pthread_join (pro, 0);

pthread_join (con, 0);

pthread_cond_destroy (&condc);

pthread_cond_destroy (&condp);
pthread_mutex_destroy (&the_mutex);

}

这道题你会答吗?花几分钟告诉大家答案吧!