作业一:创建3个线程,一个子线程拷贝文件的前一半,一个子线程拷贝后一半文件,主线程回收子线程资源。
#include <myhead.h>
//定义结构体变量
typedef struct
{const char *src_file;const char *dest_file;int start;int end;
} Copy;
//计算长度和创建目标文件
int get_len(const char *p1, const char *p2)
{int fd1 = open(p1, O_RDONLY); //打开源文件if (fd1 == -1){perror("open1");return -1;}int fd2 = open(p2, O_WRONLY | O_CREAT | O_TRUNC, 0664); //打开创建目标文件if (fd1 == -1){perror("open1");return -1;}int len = lseek(fd1, 0, SEEK_END); //计算源文件长度close(fd1);close(fd2);return len;
}
//定义写入函数
void *copy_file(void *file)
{Copy *td = (Copy *)file;int src_fd = open(td->src_file, O_RDONLY);int dest_fd = open(td->dest_file, O_WRONLY); //已只写打开目标文件if (src_fd == -1 || dest_fd == -1){perror("open");return NULL;}lseek(src_fd, td->start, SEEK_SET); //移动光标到目标位置lseek(dest_fd, td->start, SEEK_SET);char buff[5];int index;while (td->start < td->end && (index = read(src_fd, buff, sizeof(buff))) > 0) //当start>end或没有读的元素退出循环{int temp = (td->start + index > td->end) ? td->end - td->start : index; //判断应该写入的个数write(dest_fd, buff, temp);td->start += temp;}close(src_fd);close(dest_fd);pthread_exit(NULL);
}/*********************/
int main(int argc, const char *argv[])
{if (argc != 3){fprintf(stderr, "%s 源文件 目标文件", argv[0]);return -1;}const char *src_file = argv[1];const char *dest_file = argv[2];int len = get_len(src_file, dest_file);int mid = len / 2; //寻找中间位置Copy td[2] = {{src_file, dest_file, 0, mid},{src_file, dest_file, mid, len}};//创建结构体数组并初始化pthread_t tid[2];for (int i = 0; i < 2; i++){if(0 !=pthread_create(&tid[i],NULL,copy_file,&td[i]))//创建两个线程{perror("pcreat");return -1;}}for (int i = 0; i < 2; i++)//回收线程资源{pthread_join(tid[i], NULL);}printf("拷贝完成\n");pthread_exit(NULL);
}
作业二:使用无名信号量实现循环输出 春、夏、秋、冬。
#include <myhead.h>
sem_t sem1,sem2,sem3,sem4;//定义四个无名信号量
void *fun1(void *ggg)
{while(1){sem_wait(&sem4);sleep(1);printf("春\t");//写入fflush(stdout);//刷新缓存区sem_post(&sem3);}pthread_exit(NULL);
}
void *fun2(void *ggg)
{while(1){sem_wait(&sem3);sleep(1);printf("夏\t");fflush(stdout);sem_post(&sem2);}pthread_exit(NULL);
}
void *fun3(void *ggg)
{while(1){sem_wait(&sem2);sleep(1);printf("秋\t");fflush(stdout);sem_post(&sem1);}pthread_exit(NULL);
}
void *fun4(void *ggg)
{while(1){sem_wait(&sem1);sleep(1);printf("冬\t");fflush(stdout);sem_post(&sem4);}pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{pthread_t tid1,tid2,tid3,tid4;sem_init(&sem1,0,0);sem_init(&sem2,0,0);sem_init(&sem3,0,0);sem_init(&sem4,0,1);//信号4先给线程1资源if(pthread_create(&tid1,NULL,fun1,NULL)!=0)//定义输出春的函数体{perror("ptcreat1");return -1;}if(pthread_create(&tid2,NULL,fun2,NULL)!=0){perror("ptcreat2");return -1;}if(pthread_create(&tid3,NULL,fun3,NULL)!=0){perror("ptcreat3");return -1;}if(pthread_create(&tid4,NULL,fun4,NULL)!=0){perror("ptcreat3");return -1;}sem_destroy(&sem1);//销毁信号量sem_destroy(&sem2);sem_destroy(&sem3);sem_destroy(&sem4);pthread_join(tid1,NULL);//回收资源pthread_join(tid2,NULL);pthread_join(tid3,NULL);pthread_join(tid4,NULL);return 0;
}
作业三:互斥锁,无名信号量,条件变量再联系一遍。