1.将一个文件中的数据打印到终端上,类似一个cat函数
A进程读取文件中的数据
B进程将a读取的数据打印到终端上
文件打印完毕后,技术进程。
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<pthread.h>
#include<string.h>
#include<semaphore.h>
#include<sys/stat.h>
#include<fcntl.h>
char buf[10];
sem_t sem1,sem2;
void* callBack1(void* arg)
{
intret=0;
intfd=open("./01fopen.c",O_RDONLY);
while(1){
if(sem_wait(&sem1)<0){
perror("sem_waiterror");
returnNULL;
}
ret=read(fd,buf,sizeof(buf));
if(ret==0){
break;
}
if(sem_post(&sem2)<0){
perror("sem_post");
break;
}
}
pthread_exit(NULL);
}
void* callBack2(void* arg)
{
while(1){
if(sem_wait(&sem2)<0){
perror("sem_waiterror");
returnNULL;
}
printf("%s",buf);
fflush(stdout);
if(sem_post(&sem1)<0){
perror("sem_post");
break;
}
}
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem1,0,1)<0){
perror("sem_init");
return-1;
}
if(sem_init(&sem2,0,0)<0){
perror("sem_init");
return-1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callBack1,NULL)!=0){
fprintf(stderr,"pthread_createerror");
return-1;
}
if(pthread_create(&tid2,NULL,callBack2,NULL)!=0){
fprintf(stderr,"pthread_createerror");
return-1;
}
pthread_join(tid1,NULL);
pthread_detach(tid2);
sem_destroy(&sem1);
sem_destroy(&sem2);
return0;
}
2. 用条件变量实现,有编号ABC的三个线程,线程内分别打印自己的线程编号,要求打印书顺序为ABC,提示多个条件变量。
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<pthread.h>
#include<string.h>
#include<sys/stat.h>
#include<fcntl.h>
pthread_mutex_tmutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_tcond1=PTHREAD_COND_INITIALIZER;
pthread_cond_tcond2=PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3=PTHREAD_COND_INITIALIZER;
int flag=0;
void* callback_A(void* arg)
{
while(1){
pthread_mutex_lock(&mutex);
if(flag!=0){
pthread_cond_wait(&cond1,&mutex);
}
printf("A");
flag=1;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* callback_B(void* arg)
{
while(1){
pthread_mutex_lock(&mutex);
if(flag!=1){
pthread_cond_wait(&cond2,&mutex);
}
printf("B");
flag=0;
pthread_cond_signal(&cond3);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* callback_C(void* arg)
{
while(1){
pthread_mutex_lock(&mutex);
if(flag!=1){
pthread_cond_wait(&cond3,&mutex);
}
printf("C");
fflush(stdout);
flag=0;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_ttidA,tidB,tidC;
if(pthread_create(&tidA,NULL,callback_A,NULL)){
fprintf(stderr,"pthread_createfailed\n");
return-1;
}
pthread_detach(tidA);
if(pthread_create(&tidB,NULL,callback_B,NULL)){
fprintf(stderr,"pthread_createfailed\n");
return-1;
}
pthread_detach(tidB);
if(pthread_create(&tidC,NULL,callback_C,NULL)){
fprintf(stderr,"pthread_createfailed\n");
return-1;
}
pthread_join(tidC,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
return0;
}