1.创建两个线程,实现将一个文件的内容打印到终端上, 类似cat一个文件
a.一个线程读取文件中的内容;b.另一个线程将读取到的内容打印到终端上。
ubuntu@ubuntu:~/32/work/io/day7$ cat pthread_cat.c
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<semaphore.h>
pthread_mutex_t mutex;
sem_t sem1,sem2;
char c;
void* callBack1(void* fd_r)//void* arg = &fd_r
{
ssize_t res;
while(1)
{
sem_wait(&sem1);
res = read(*(int*)fd_r,&c,sizeof(c));
if(res<0)
{
perror("read");
return NULL;
}
if(0==res)
break;
sem_post(&sem2);
}
printf("读取完毕\n");
pthread_exit(NULL);
}
void* callBack2(void* arg)
{
ssize_t res;
while(1)
{
sem_wait(&sem2);
res = write(1,&c,sizeof(c));
if(res<0)
{
perror("write");
return NULL;
}
sem_post(&sem1);
}
printf("打印完毕\n");
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建信号灯
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
//打开源文件
int fd_r = open("../day6/semaphore.c",O_RDONLY);
if(fd_r<0)
{
perror("open");
return -1;
}
//创建一个线程读取文件中的内容
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callBack1,(void*)&fd_r)!=0)
{
fprintf(stderr,"pthread_create failed\n");
return -1;
}
//创建一个线程将读取到的内容打印到终端
if(pthread_create(&tid2,NULL,callBack2,NULL)!=0)
{
fprintf(stderr,"pthread_create failed\n");
return -1;
}
//阻塞等待分支线程运行完毕
pthread_join(tid1,NULL);
// pthread_join(tid2,NULL);
//关闭文件
close(fd_r);
return 0;
}
2.现有ID号为a b c的三个线程,每个线程的任务都是循环打印自己ID号,要求打印的顺序为abc。
ubuntu@ubuntu:~/32/work/io/day7$ cat abcthree.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<semaphore.h>
#include<pthread.h>
sem_t sem1,sem2,sem3;
void* A(void* arg)//void* arg=&tid1
{
while(1)
{
sem_wait(&sem1);
fprintf(stdout,"a\t");
fprintf(stdout,"%ld\n",*(pthread_t*)arg);
sem_post(&sem2);
}
pthread_exit(NULL);
}
void* B(void* arg)
{
while(1)
{
sem_wait(&sem2);
fprintf(stdout,"b\t");
fprintf(stdout,"%ld\n",*(pthread_t*)arg);
sem_post(&sem3);
}
pthread_exit(NULL);
}
void* C(void* arg)
{
while(1)
{
sem_wait(&sem3);
fprintf(stdout,"c\t");
fprintf(stdout,"%ld\n",*(pthread_t*)arg);
sem_post(&sem1);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建三个线程
pthread_t tid1,tid2,tid3;
pthread_create(&tid1,NULL,A,&tid1);
pthread_create(&tid2,NULL,B,&tid2);
pthread_create(&tid3,NULL,C,&tid3);
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
pthread_join(tid1,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
return 0;
}