1.使用两个线程完成两个文件的拷贝,分支线程1完成前一半内容拷贝,分支线程2完成后一半内容的拷贝,主线程完成资源的回收.
#include
// 定义结构体 存储从终端输入的文件名和文件长度;
typedef struct filecpy {
const char* src;
const char* dst;
int star;
int len;
} fil;
// 计算文件大小
int lenths(const char* srcf, const char* dstf)
{
// 以只读方式打开源文件
int srct = -1;
if ((srct = open(srcf, O_RDONLY)) == -1) {
perror("open src error");
return -1;
}
// 以只写方式打开目标文件有则清空无则创建
int dstt = -1;
if ((dstt = open(dstf, O_WRONLY | O_CREAT | O_TRUNC, 0664)) == -1) {
perror("open dst error");
return -1;
}
int lens = lseek(srct, 0, SEEK_END); // 将光标定位至结尾
close(srct);
close(dstt);
return lens;
}
// 拷贝
int copy(const char* srcf, const char* dstf, int star, int len)
{
int srct = -1;
if ((srct = open(srcf, O_RDONLY)) == -1) {
perror("open src error");
return -1;
}
int dstt = -1;
if ((dstt = open(dstf, O_WRONLY)) == -1) {
perror("open dst error");
return -1;
}
// 将光标定位至同一位置;
lseek(srct, star, SEEK_SET);
lseek(dstt, star, SEEK_SET);
int res = 0;
int sum = 0;
char buf[128] = ""; // 容器
while (1) {
res = read(srct, buf, sizeof(buf));
sum += res;
if (res == 0 | sum > len) {
write(dstt, buf, res - sum + len);
break;
}
write(dstt, buf, res); // 将源文件拷贝给目标文件
}
close(srct);
close(dstt);
return 0;
}
// 第一个分支线程负责拷贝上半部分
void* task(void* acg)
{
fil tm = *((fil*)acg);
copy(tm.src, tm.dst, tm.star, tm.len);
pthread_exit(NULL);
}
int main(int argc, const char* argv[])
{
// 终端输入
if (argc != 3) {
printf("输入格式错误\n");
printf("such as:./a.out s.txt ss.txt\n");
}
int lens = lenths(argv[1], argv[2]);
fil tm[2] = { { argv[1], argv[2], 0, lens },
{ argv[1], argv[2], lens / 2, lens - lens / 2 } };
// 创建第一个分支线程
pthread_t pid1 = -1;
pthread_create(&pid1, NULL, task, &tm[0]);
// 创建第二个分支线程
pthread_t pid2 = -1;
pthread_create(&pid2, NULL, task, &tm[1]);
// 主线程
pthread_join(pid1, NULL);
pthread_join(pid2, NULL);
printf("拷贝完成\n");
return 0;
}
2.熟悉互斥锁
#include
int money=10000;
//定义锁
pthread_mutex_t mutex;
//线程体函数
void *task(void *arg)
{
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
while (1)
{
pthread_mutex_lock(&mutex);//上
money=money-200;
printf("主线程拿走200块,还剩%d\n",money);
pthread_mutex_unlock(&mutex);//解
sleep(1);
}
}
/************主*************/
int main(int argc,const char *argv[])
{
//初始化
pthread_mutex_init (&mutex,NULL);
//定义一个线程号
pthread_t tid = -1;
//创建一个线程
if(pthread_create(&tid,NULL,task,NULL)!=0)
{
perror("tid cread error");
return -1;
}
while(1)
{
pthread_mutex_lock(&mutex);//上
money=money-400;
printf("分支线程拿走400块,还剩%d\n",money);
pthread_mutex_unlock(&mutex);//解
sleep(1);
}
pthread_join(tid,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}