这份代码也是基于上两篇博文修改,利用信号量实现了条件变量:
源码1:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
typedef struct
{
int res;
sem_t sem;
}Result;
void * func_set(void *arg)
{
Result *r=(Result *)arg;
int i=1,sum=0;
for(;i<=100;i++)
{
sum=sum+i;
}
r->res=sum;
printf("the pthread %lx has write done\n",pthread_self());
sem_post(&r->sem);
printf("I am ready to broadcast\n");
}
void *func_get(void *arg)
{
Result *r=(Result *)arg;
sem_wait(&r->sem);
printf("I have receive the infomation\n");
int res=r->res;
printf("the pthread %lx read the result is %d\n",pthread_self(),res);
}
int main(void)
{
int err;
pthread_t rabbit,turtle;
Result r;
sem_init(&r.sem,0,0);
if((err=pthread_create(&rabbit,NULL,func_set,(void *)&r))!=0)
{
perror("pthread_create error");
}
if((err=pthread_create(&turtle,NULL,func_get,(void *)&r))!=0)
{
perror("pthread_create error");
}
pthread_join(rabbit,NULL);
pthread_join(turtle,NULL);
sem_destroy(&r.sem);
printf("control thread id: %lx\n",pthread_self());
printf("finished!\n");
return 0;
}
源码2:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
typedef struct
{
int value;
sem_t sem1;
sem_t sem2;
}Result;
void set_data(Result *r,int value)
{
r->value=value;
}
int get_data(Result *r)
{
return r->value;
}
void * func_set(void *arg)
{
Result *r=(Result *)arg;
int i=1;
for(;i<=100;i++)
{
set_data(r,i+100);
printf("1:the pthread %lx has set the date %d\n",pthread_self(),i+100);
sem_post(&r->sem1);
printf("1:I am ready to broadcast\n");
//这个时候线程等待另外一个线程通知
sem_wait(&r->sem2);
printf("2:I have receive the infomation2\n");
int res=get_data(r);
printf("2:the pthread %lx read the result is %d\n",pthread_self(),res);
//代码包括在这里
}
}
void *func_get(void *arg)
{
Result *r=(Result *)arg;
int i=1;
for(;i<=100;i++)
{
sem_wait(&r->sem1);
printf("1:I have receive the infomation\n");
int res=get_data(r);
printf("1:the pthread %lx read the result is %d\n",pthread_self(),res);
//现在是双向的,所以需要去判断另外一个线程是否准备好,注意这里要用第二把所和第二个条件变量
set_data(r,i+100);
printf("2:the pthread %lx has set the date %d\n",pthread_self(),i+100);
sem_post(&r->sem2);
printf("2:I am ready to broadcast2\n");
//代码写在这里
}
}
int main(void)
{
int err;
pthread_t rabbit,turtle;
Result r;
sem_init(&r.sem1,0,0);
sem_init(&r.sem2,0,0);
if((err=pthread_create(&rabbit,NULL,func_set,(void *)&r))!=0)
{
perror("pthread_create error");
}
if((err=pthread_create(&turtle,NULL,func_get,(void *)&r))!=0)
{
perror("pthread_create error");
}
pthread_join(rabbit,NULL);
pthread_join(turtle,NULL);
sem_destroy(&r.sem1);
sem_destroy(&r.sem2);
printf("control thread id: %lx\n",pthread_self());
printf("finished!\n");
return 0;
}