64,646
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#define SIZE 4
struct product
{
sem_t sem_empty;\\定义两个信号量,防止下标访问越界,和线程同步问题
sem_t sem_full;
pthread_mutex_t mutexlock;
int pos;
int buf[SIZE];
};
void init(struct product *t)
{
pthread_mutex_init(&t->mutexlock,NULL);
sem_init(&t->sem_full,0,SIZE);
sem_init(&t->sem_empty,0,0);
t->pos =-1;
}
void put(struct product *t,int data)
{
sem_wait(&t->sem_full);
pthread_mutex_lock(&t->mutexlock);
t->pos = t->pos +1;
t->buf[t->pos] = data;
printf("Thread %d put a data:%d to pos%d\n",pthread_self(),data,t->pos);
sem_post(&t->sem_empty);
pthread_mutex_unlock(&t->mutexlock);
}
void get(struct product *t)
{
sem_wait(&t->sem_empty);
pthread_mutex_lock(&t->mutexlock);
printf("Thread %d get a data:%d from pos%d\n",pthread_self(),t->buf[t->pos],t->pos);
t->buf[t->pos] = -1;
t->pos = t->pos -1;
sem_post(&t->sem_full);
pthread_mutex_unlock(&t->mutexlock);
}
struct product pdt;
void *putter()
{
int n;
for(n=0;n<8;n++)
put(&pdt,n);
}
void *getter()
{
int n;
for(n=0;n<8;n++)
get(&pdt);
}
int main(void)
{
pthread_t pt1,pt2,gt1,gt2;
void *retval;
init(&pdt);
pthread_create(&pt1,NULL,putter,0);
pthread_create(&pt2,NULL,putter,0);
pthread_create(>1,NULL,getter,0);
pthread_create(>2,NULL,getter,0);
pthread_join(pt1,&retval);
pthread_join(pt2,&retval);
pthread_join(gt1,&retval);
pthread_join(gt2,&retval);
return 0;
}