#include <myhead.h>
void *task_one(void *arg)
{
int fd1=open("./text",O_RDONLY);
if(fd1<0)
{
perror("open");
return NULL;
}
int fd2=open("./1text",O_WRONLY);
if(fd2<0)
{
perror("open");
return NULL;
}
int len=lseek(fd1,0,SEEK_END);
lseek(fd1,0,SEEK_SET);
lseek(fd2,0,SEEK_SET);
char a[128];
int i;
int sum=0;
int res=0;
while(1)
{
res=read(fd1,a,sizeof(a));
sum=sum+res;
if(res==0|sum>=(len/2))
{
write(fd2,a,res-(sum-len/2));
break;
}
write(fd2,a,res);
}
close(fd1);
close(fd2);
}
void *task_two(void *arg)
{
int fd1=open("./text",O_RDONLY);
if(fd1<0)
{
perror("open");
return NULL;
}
int fd2=open("./1text",O_WRONLY);
if(fd2<0)
{
perror("open");
return NULL;
}
int len=lseek(fd1,0,SEEK_END);
lseek(fd1,len/2,SEEK_SET);
lseek(fd2,len/2,SEEK_SET);
char a[128];
int i;
int sum=0;
int res=0;
while(1)
{
res=read(fd1,a,sizeof(a));
sum=sum+res;
if(res==0|sum>=(len-(len-len/2)))
{
write(fd2,a,res-(sum-len/2));
break;
}
write(fd2,a,res);
}
close(fd1);
close(fd2);
}
int main(int argc, const char *argv[])
{
pthread_t tidf=-1;
pthread_t tids=-1;
if(pthread_create(&tidf,NULL,task_one,NULL)!=0)
{
printf("error\n");
return -1;
}
if(pthread_create(&tids,NULL,task_two,NULL)!=0)
{
printf("error\n");
return -1;
}
pthread_join(tidf,NULL);
pthread_join(tids,NULL);
return 0;
}
2
#include <myhead.h>
int money=100;
pthread_mutex_t mutex;
void *task(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);//上锁
money=money-10;
printf("-10还剩:%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 error\n");
return -1;
}
while(1)
{
pthread_mutex_lock(&mutex);
money=money-1;
printf("-1还剩:%d\n",money);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_join(tid,NULL);
pthread_mutex_destroy(&mutex);//摧毁锁
return 0;
}