要求创建两个线程,实现文件打印到终端上,类似cat一个文件:
A线程读取文件中的内容
B线程将A线程中读取到的数据打印到终端上
当文件打印完毕后,结束进程。
代码:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//宏定义互斥锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//宏定义条件变量
char str[64] = "";//存放读取数据以及写入数据的中间数组
int flag = 0;//条件变量的辅助标志位
ssize_t res;//接收read的返回值,判断读取状态,判断该写入多少数据
void* read1(void *arg)
{
int fd;
if((fd = open("./01.c",O_RDONLY)) < 0)//以读取的方式打开文件
{
perror("open");
return NULL;
}
//读取文件中的数据到数组中,需要先读取再写入
while(1)
{
pthread_mutex_lock(&mutex);//锁定以下程序完整运行
if(0 != flag)//标志位不为0时
{
pthread_cond_wait(&cond,&mutex);//使读取线程睡眠并将互斥锁解开
}
bzero(str,sizeof(str));//清空中间数组
res = read(fd,str,sizeof(str));//将文件内容读取到数组中
if(res < 0)
{
perror("read");
return NULL;
}
else if(res == 0)//读取完毕退出线程
{
printf("读取结束\n");
pthread_mutex_unlock(&mutex);//锁定解除
break;
}
flag = 1;//标志位置一,防止读线程再次运行覆盖未写入的数据
pthread_cond_signal(&cond);//唤醒写入线程
pthread_mutex_unlock(&mutex);//锁定解除
}
if(close(fd) < 0)//关闭打开的文件
{
perror("close");
return NULL;
}
pthread_exit(NULL);
}
void* write1(void *arg)
{
ssize_t res1;//接受write的返回值,判断写入的状态
while(1)
{
pthread_mutex_lock(&mutex);//锁定以下程序
if(1 != flag)//标志位不为1时
{
pthread_cond_wait(&cond,&mutex);//使线程睡眠,并解锁
}
if(0 == res)
{
printf("写入完毕\n");
pthread_exit(NULL);
}
res1 = write(1,str,res);//将数组中的内容写入终端
if(res1 < 0)//如果写入失败则退出线程
{
perror("write");
}
flag = 0;
pthread_cond_signal(&cond);//唤醒写入线程
pthread_mutex_unlock(&mutex);//锁定解除
}
}
int main(int argc, const char *argv[])
{
//创建读,写线程
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,read1,NULL) != 0)//文件读取线程,将文件描述符传参过去
{
fprintf(stderr,"pthread_create failed:%d\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,write1,NULL) != 0)//终端写入线程
{
fprintf(stderr,"pthread_create failed:%d\n",__LINE__);
return -1;
}
pthread_join(tid2,NULL);
pthread_detach(tid1);
pthread_mutex_destroy(&mutex);//销毁互斥锁
pthread_cond_destroy(&cond);//销毁条件变量
return 0;
}
现象: