1.使用三个线程完成两个文件的拷贝工作,线程1拷贝前一半,线程2拷贝后-半,主线程主要用于回收子线程的资源
#include <head.h>
pthread_mutex_t mutex;
void* fun1(void* arg)
{
pthread_mutex_lock(&mutex);
int fp1=open("./copy.c",O_RDONLY);
if(fp1<0)
{
ERR_MSG("open");
return NULL;
}
int fp2=open("./stick.c",O_WRONLY);
if(fp2<0)
{
ERR_MSG("open");
return NULL;
}
off_t size=lseek(fp1,0,SEEK_END);
lseek(fp1,0,SEEK_SET);
lseek(fp2,0,SEEK_SET);
char buf;
for(int i=0;i<(size/2);i++)
{
int ret=read(fp1,&buf,sizeof(buf));
write(fp2,&buf,ret);
}
printf("前半部分完毕\n");
close(fp1);
close(fp2);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void* fun2(void* arg)
{
pthread_mutex_init(&mutex,NULL);
pthread_mutex_lock(&mutex);
int fp1=open("./copy.c",O_RDONLY,0764);
if(fp1<0)
{
ERR_MSG("open");
return NULL;
}
int fp2=open("./stick.c",O_WRONLY);
if(fp2<0)
{
ERR_MSG("open");
return NULL;
}
off_t size=lseek(fp1,0,SEEK_END);
lseek(fp1,(size/2),SEEK_SET);
lseek(fp2,(size/2),SEEK_SET);
char buf;
while(1)
{
int ret=read(fp1,&buf,sizeof(buf));
if(ret==0)
{
break;
}
write(fp2,&buf,ret);
}
printf("后半部分完毕\n");
close(fp1);
close(fp2);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy;
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
int fp2=open("./stick.c",O_RDWR | O_TRUNC |O_CREAT,0764);
if(fp2<0)
{
ERR_MSG("open");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
{
printf("tid1 create error\n");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
{
printf("tid2 create error\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
2.使用三个线程完成, 第一个线程输出A,第二个线程输出B,第三个线程输出C,最终输出的结果为:
ABCABCABCABCABC
#include <head.h>
sem_t sem1,sem2,sem3;
void*fun1(void* arg)
{
int num=5;
while(num--)
{
sem_wait(&sem2);
fprintf(stderr,"C");
sem_post(&sem3);
}
pthread_exit(NULL);
}
void*fun2(void* arg)
{
int num=5;
while(num--)
{
sem_wait(&sem1);
fprintf(stderr,"B");
sem_post(&sem2);
}
pthread_exit(NULL);
}
void*fun3(void* arg)
{
int num=5;
while(num--)
{
sem_post(&sem1);
fprintf(stderr,"A");
sem_wait(&sem3);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
{
printf("tid1 create error\n");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
{
printf("tid2 create error\n");
return -1;
}
if(pthread_create(&tid3,NULL,fun3,NULL)!=0)
{
printf("tid3 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);
puts("");
return 0;
}