2.创建两个线程,实现将一个文件的内容打印到终端上,类似cat一个文件
一个线程读取文件中的内容
另一个线程将读取到的内容打印到终端上。
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>
#include<strings.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
struct info
{
int fp;
int fw;
off_t n;
};
char arr;
int flag=1;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void* bad1(void * arg)
{
int fp=((struct info *)arg)->fp;
off_t n=((struct info *)arg)->n;
off_t m=n/2;
off_t offsize=0;
while(1)
{
pthread_mutex_lock(&mutex);
lseek(fp,offsize,SEEK_SET);
read(fp,&arr,1);
if(lseek(fp,0,SEEK_CUR)>n)
{
break;
}
if(flag!=1)
{
pthread_cond_wait(&cond,&mutex);
}
offsize=lseek(fp,0,SEEK_CUR);
flag=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
printf("pick one over\n");
pthread_exit(NULL);
}
void* bad2(void * arg)
{
int aa=1,bb=1;
off_t n=((struct info *)arg)->n;
off_t m=n/2;
off_t count=1;
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=0)
{
pthread_cond_wait(&cond,&mutex);
}
printf("%c",arr);
count++;
if(count>=n)
{
break;
}
flag=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
// printf("b=%d\n",b);
int fp=-1,fw=-1;
fp=open(argv[1],O_RDONLY);
if(0>fp)
{
printf("%d\t",__LINE__);
perror("open");
return -1;
}
off_t n=lseek(fp,0,SEEK_END);
struct info file;
file.fp=fp;
file.fw=fw;
file.n=n;
pthread_t tid1;
if(pthread_create(&tid1,NULL,bad1,(void *)&file))
{
fprintf(stderr,"pthread_creat1 is flase.%d\n",__LINE__);
return -1;
}
pthread_t tid2;
if(pthread_create(&tid2,NULL,bad2,(void *)&file))
{
fprintf(stderr,"pthread_creat2 is flase.%d\n",__LINE__);
return -1;
}
pthread_join(tid2,NULL);
close(fw);
close(fp);
pthread_mutex_destroy(&mutex);
return 0;
}