chinaunix网友2010-07-04 03:32
#include
#include
#define buffer_size 16
struct prodcons {
int buffer[buffer_size];
pthread_mutex_t lock;
int readpos,writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init (struct prodcons *b) {
pthread_mutex_init(&b->lock,null);
pthread_cond_init(&b->notempty,null);
pthread_cond_init(&b->notfull,null);
b->readpos=0;
b->writepos=0;
}
void put(struct prodcons *b, int data) {
{
pthread_mutex_lock(&b->lock);
if((b->writepos 1)%buffer_size==b->readpos) {
pthread_cond_wait(&b->notfull,&b->lock);
}
b->buffer[b->writepos]=data;
b->writepos ;
if(b->writepos>=buffer_size)
b->writepos=0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct prodcons *b)
{
int data;
pthread_mutex_lock(&b->lock);
if(b->writepos==b->readpos) {
pthread_cond_wait(&b->notempty,&b->lock);
}
data=b->buffer[b->readpos];
b->readpos ;
if(b->readpos>=buffer_size)
b->readpos=0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
#define over (-1)
struct prodcons buffer;
void *producer(void *data)
{
int n;
for(n=0;n<10000;n )
{
printf(“%d---->\n”,n);
put(&buffer,n);
}
put(&buffer,over);
return null;
}
void *consumer(void *data)
{
int d;
while(1)
{
d=get(&buffer);
if(d==over)
break;
printf(“---->%d\n”,d);
}
return null;
}
int main(void)
{
pthread_t th_a,th_b;
void *retval;
init(&buffer);
pthread_create(&th_a,null,producer,0);
pthread_create(&th_b,null,consumer,0);
pthread_join(th_a,&retval);
pthread_join(th_b,&retval);
return 0;
}
高人,帮个忙把这段程序加上注释呗,详细的,多谢了
| |