从上一个小测试当中,我们会发现线程之间存在争夺问题,所以在这里用上了信号锁
#include
#include
#include
#include
#include
#include
#include
#define MAX_SIZE 5
struct data_struct{
time_t the_time;
pthread_t pid;
int order;
}Pro[MAX_SIZE];
sem_t sem1,sem2;//signal
pthread_mutex_t mutex1,mutex2;
int in = 0,out = 0;
void producethread(void* arg);
void customerthread(void* arg);
int main(int argc,const char* argv[])
{
pthread_t pro1,pro2;
pthread_t cus1,cus2;
sem_init(&sem1,0,4);
sem_init(&sem2,0,0);
pthread_mutex_init(&mutex1,NULL);
pthread_mutex_init(&mutex2,NULL);
pthread_create(&pro1,NULL,(void*)producethread,NULL);
pthread_create(&pro2,NULL,(void*)producethread,NULL);
pthread_create(&cus1,NULL,(void*)customerthread,NULL);
pthread_create(&cus2,NULL,(void*)customerthread,NULL);
//pthread_mutex_destory(&mutex1);
//pthread_mutex_destory(&mutex2);
pthread_join(pro1,NULL);
pthread_join(pro2,NULL);
pthread_join(cus1,NULL);
pthread_join(cus2,NULL);
exit(EXIT_SUCCESS);
}
void producethread(void* arg)
{
int i;
for(i=0;i<10;i++)
{
//sem_wait(&sem1);//wrire 信号量通知写 说明消费者以及读完了
pthread_mutex_lock(&mutex1);
Pro[in%MAX_SIZE].pid = pthread_self();
Pro[in%MAX_SIZE].order = i;
time(&Pro[in%MAX_SIZE].the_time);
in++;
//sem_post(&sem2);
pthread_mutex_unlock(&mutex1);
sleep(2);
}
}
void customerthread(void* arg)
{
int counter=0;
while(1){
if(counter == 10)
{
break;
}
//sem_wait(&sem2);
pthread_mutex_lock(&mutex2);
if(out%2 == 0)
{
printf("customer1:");
}
else{
printf("customer2:");
}
printf("order=%2d thread_id=%5d time:%s",(int)Pro[out%MAX_SIZE].order,(int)Pro[out%MAX_SIZE].pid,ctime(&Pro[out%MAX_SIZE].the_time));
out++;
//sem_post(&sem1);
pthread_mutex_unlock(&mutex2);
sleep(3);
counter++;
}
}
刚开始写的时候没有加入信号量来进行交互,得到了以下的结果
发现并不是符合我们预期的输出,会出现数据杂乱,错读重复的现象,说明写入和读出是由CPU随机调度的.
所以在这里加上了sem_t 信号量,来进行线程间的互相通知,消费者线程利用同一个锁互斥,不会造成混乱,同时通知生产者是否要生成数据,生产者线程也通过另一个锁互斥,不会不按顺序生产,这样的话就能够做到生产完成之后发送信号,消费者进行消费.