#include <myhead.h>
sem_t sem1;
sem_t sem2;
sem_t sem3;
void* funca(void* fd)
{
while(1)
{
sem_wait(&sem3);
printf("A\n");
sem_post(&sem1);
}
return NULL;
}
void* funcb(void* fd)
{
while(1)
{
sem_wait(&sem1);
printf("B\n");
sem_post(&sem2);
}
return NULL;
}
void* funcc(void* fd)
{
while(1)
{
sem_wait(&sem2);
printf("C\n");
sem_post(&sem3);
}
return NULL;
}
int main(int argc, const char *argv[])
{
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
sem_init(&sem3,0,1);
pthread_t tid1;
if(pthread_create(&tid1,NULL,funca,NULL)!=0)
{
printf("pthread create error!\n");
return -1;
}
pthread_t tid2;
if(pthread_create(&tid2,NULL,funcb,NULL)!=0)
{
printf("pthread create error!\n");
return -1;
}
pthread_t tid3;
if(pthread_create(&tid3,NULL,funcc,NULL)!=0)
{
printf("pthread create error!\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
return 0;
}
#include <myhead.h>
pthread_mutex_t mutex;
typedef struct fdnode
{
int fd1;
int fd2;
}fdall;
void* func(void* fd)
{
fdall* fk=(fdall*)fd;
//文件大小
struct stat buf;
if(stat("/home/ubuntu/process/test1.c",&buf)<0)
{
perror("stat");
return NULL;
}
off_t size=buf.st_size;
int count=0;
char temp=0;
while(1)
{
pthread_mutex_lock(&mutex);
lseek(fk->fd1,size/2,SEEK_SET);
lseek(fk->fd2,size/2,SEEK_SET);
lseek(fk->fd1,count,SEEK_CUR);
lseek(fk->fd2,count,SEEK_CUR);
if(read(fk->fd1,&temp,1)==0)
break;
write(fk->fd2,&temp,1);
count++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* func1(void* fd)
{
fdall* fk=(fdall*)fd;
//文件大小
struct stat buf;
if(stat("/home/ubuntu/process/test1.c",&buf)<0)
{
perror("stat");
return NULL;
}
off_t size=buf.st_size;
int count=0;
char temp;
while(count<size/2)
{
pthread_mutex_lock(&mutex);
lseek(fk->fd1,count,SEEK_SET);
lseek(fk->fd2,count,SEEK_SET);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mutex,NULL);
fdall fd;
int fd1=open("/home/ubuntu/process/test1.c",O_RDONLY);
int fd2=open("/home/ubuntu/process/newtest1.c",O_RDWR|O_CREAT|O_TRUNC,0664);
fd.fd1=fd1;
fd.fd2=fd2;
pthread_t tid;
if(pthread_create(&tid,NULL,func,&fd)!=0)
{
printf("error!\n");
return -1;
}
pthread_t tid1;
if(pthread_create(&tid1,NULL,func1,&fd)!=0)
{
return -1;
}
read(fk->fd1,&temp,1);
write(fk->fd2,&temp,1);
count++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mutex,NULL);
fdall fd;
int fd1=open("/home/ubuntu/process/test1.c",O_RDONLY);
int fd2=open("/home/ubuntu/process/newtest1.c",O_RDWR|O_CREAT|O_TRUNC,0664);
fd.fd1=fd1;
fd.fd2=fd2;
pthread_t tid;
if(pthread_create(&tid,NULL,func,&fd)!=0)
{
printf("error!\n");
return -1;
}
pthread_t tid1;
if(pthread_create(&tid1,NULL,func1,&fd)!=0)
{
return -1;
}
pthread_join(tid,NULL);
pthread_join(tid1,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}