1.
#include
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
//pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
char buf[20]="";
int flag=0;
void *fun_a(void *arg)
{
ssize_t res;
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=0)
pthread_cond_wait(&cond1,&mutex);
res=read(*((int *)arg),buf,sizeof(buf));
if(res==0)
break;
flag=1;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *fun_b(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=1)
pthread_cond_wait(&cond1,&mutex);
write(1,buf,sizeof(buf));
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
int fd=open("./02_fprintf.c",O_RDONLY);
pthread_create(&tid1,NULL,fun_a,(void*)&fd);
pthread_create(&tid2,NULL,fun_b,(void*)&fd);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
close(fd);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
// pthread_cond_destroy(&cond2);
return 0;
}
2.
#include
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
int flag=0;
void *fun_a(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=0)
pthread_cond_wait(&cond1,&mutex);
printf("%c",*(char*)arg);
flag=1;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *fun_b(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=1)
pthread_cond_wait(&cond2,&mutex);
printf("%c",*(char*)arg);
flag=2;
pthread_cond_signal(&cond3);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *fun_c(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=2)
pthread_cond_wait(&cond3,&mutex);
printf("%c\n",*(char*)arg);
flag=0;
sleep(1);
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2,tid3;
char a='A';
char b='B';
char c='C';
pthread_create(&tid1,NULL,fun_a,(void*)&a);
pthread_create(&tid2,NULL,fun_b,(void*)&b);
pthread_create(&tid3,NULL,fun_c,(void*)&c);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
return 0;
}
3.
#include
char buf[]="1234567";
sem_t sem1,sem2;
void *fun_a(void *arg)
{
while(1)
{
sem_wait(&sem2);
printf("%s\n",buf);
//sleep(1);
sem_post(&sem1);
sleep(1);
}
pthread_exit(NULL);
}
void *fun_b(void *arg)
{
sem_t *sem=(sem_t*)arg;
char tmp=0;
while(1)
{
sem_wait(&sem1);
for(int i=0;i