一、创建两个线程,实现将一个文件的内容打印到终端上,类似cat一个文件
1.一个线程读取文件中的内容;
2.另一个线程将读取到的内容打印到终端上。
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
sem_t sem1,sem2;
char buf[32];
int flag = 0;
void * callBack1(void *arg)
{
//读取文件中的内容
int fd = open("./02_pthread_mutex.c",O_RDONLY);
if(fd < 0)
{
perror("open");
return NULL;
}
while(1)
{
sem_wait(&sem1);
bzero(buf,sizeof(buf));
ssize_t res = 0;
res = read(fd,buf,sizeof(buf));
if(0 == res)
{
flag = 1;
printf("读取完毕,线程1结束\n");
sem_post(&sem2);
pthread_exit(NULL);
}
sem_post(&sem2);
}
}
void * callBack2(void *arg)
{
//读取到的内容,打印到终端上
while(1)
{
sem_wait(&sem2);
printf("%s",buf);
if(1 == flag)
{
printf("打印完毕,线程2结束\n");
pthread_exit(NULL);
}
sem_post(&sem1);
}
}
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_create failed%d\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callBack2,NULL) != 0)
{
fprintf(stderr,"pthread_create failed%d\n ",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
二、现有ID号为a b c的三个线程,每个线程的任务都是循环打印自己id号,要求打印的顺序为abc
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem_a,sem_b,sem_c;
void * callBack_a(void *arg)
{
while(1)
{
sem_wait(&sem_a);
printf("a = %ld\n",*(pthread_t *)arg);
sem_post(&sem_b);
}
}
void * callBack_b(void *arg)
{
while(1)
{
sem_wait(&sem_b);
printf("b = %ld\n",*(pthread_t *)arg);
sem_post(&sem_c);
}
}
void * callBack_c(void *arg)
{
while(1)
{
sem_wait(&sem_c);
printf("c = %ld\n",*(pthread_t *)arg);
sem_post(&sem_a);
}
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem_a,0,1) != 0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem_b,0,0) != 0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem_c,0,0) != 0)
{
perror("sem_init");
return -1;
}
pthread_t tid_a,tid_b,tid_c;
if((pthread_create(&tid_a,NULL,callBack_a,&tid_a)) !=0)
{
fprintf(stderr,"pthread_create failed %d\n",__LINE__);
return -1;
}
if((pthread_create(&tid_b,NULL,callBack_b,&tid_b)) !=0)
{
fprintf(stderr,"pthread_create failed %d\n",__LINE__);
return -1;
}
if((pthread_create(&tid_c,NULL,callBack_c,&tid_c)) !=0)
{
fprintf(stderr,"pthread_create failed %d\n",__LINE__);
return -1;
}
pthread_join(tid_a,NULL);
pthread_join(tid_b,NULL);
pthread_join(tid_c,NULL);
sem_destroy(&sem_a);
sem_destroy(&sem_b);
sem_destroy(&sem_c);
return 0;
}