1.。
2.
#include "myhead.h"
void *task(void *arg){
printf("我是分支线程1.tid=%#lx\n",pthread_self());
int fd1=-1;//创建并打开文件2,
if((fd1=open("./1text.txt",O_WRONLY|O_CREAT,0664))==-1){
perror("create 1txt error");
}
int fd2=-1;//打开被拷贝文件
if((fd2=open("./text.txt",O_RDONLY))==-1){
perror("read error");
}
int len=lseek(fd2,0,SEEK_END);//计算文件长度
lseek(fd2,0,SEEK_SET);//光标定位到开头
printf("len=%d\n",len);
char rbuf[128];
for(int i=0;i<(len/2);i++){//拷贝一半
read(fd2,rbuf,1);
write(fd1,rbuf,1);
write(1,rbuf,1);
}
close(fd1);
close(fd2);
puts("");
pthread_exit(NULL);//结束分支线程1
}
void *task1(void *arg){
printf("我是分支线程2,tid=%#lx\n",pthread_self());
int fd1=-1;
if((fd1=open("./1text.txt",O_WRONLY|O_CREAT,0664))==-1){
perror("create 1txt error");
}
int fd2=-1;
if((fd2=open("./text.txt",O_RDONLY))==-1){
perror("read error");
}
int len=lseek(fd2,0,SEEK_END);
printf("len=%d\n",len);
lseek(fd2,(len/2),SEEK_SET);//光标定位到一半的位置
lseek(fd1,(len/2),SEEK_SET);
char rbuf[128];
for(int i=(len/2);i<len;i++){//拷贝另一半
read(fd2,rbuf,1);
write(fd1,rbuf,1);
write(1,rbuf,1);
}
puts("");
close(fd1);
close(fd2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid[2]={-1,-1};//创建两个子进程
if(pthread_create(&tid[0],NULL,task,NULL)!=0){
printf("task create error\n");
return -1;
}
if(pthread_create(&tid[1],NULL,task1,NULL)!=0){
printf("task1 cteate error\n");
return -1;
}
printf("我是主线程,线程号为:%#lx",pthread_self());
int fd=-1;//穿件一个文件,写入东西
if((fd=open("./text.txt",O_RDWR|O_CREAT|O_TRUNC,0664))==-1){
perror("create txt error");
return -1;
}
char buf[128]="hello world";
write(fd,buf,strlen(buf));
close(fd);
pthread_join(tid[0],NULL);//回收资源
pthread_join(tid[1],NULL);
return 0;
}
3.
#include "myhead.h"
int money=5000;
pthread_mutex_t mutex;
void *task(void *arg){
while(1){
pthread_mutex_lock(&mutex);
money=money-50;
printf("李四线程取了50元还剩%d元\n",money);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid=-1;
pthread_mutex_init(&mutex,NULL);
if(pthread_create(&tid,NULL,task,NULL)!=0){
printf("tid create error");
return -1;
}
while(1){
pthread_mutex_lock(&mutex);
money=money-100;
printf("张三线程取了100元还剩%d元\n",money);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_join(tid,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}