进程代码并不是一口气跑完的,而是通过时间片来分配的。如:两个进程任务,时间片分配固定的时间运行,运行一个,直接跑下一个,而且进程数据是共享的,所以数据容易错乱。
引入flag,作为条件, 可以完成一个线程再完成另一个,不会错乱。但这非常浪费
#include<stdio.h>
#include<pthread.h>
#include<string.h>
char str[] = "1234567";
int flag = 0;
void* callBack_print(void*arg)
{
while(1)
{
if(0 == flag)
{
printf("%s\n",str);
flag = 1;
}
}
pthread_exit(NULL);
}
void* callBack_reaerve(void*arg)
{
int i = 0;
char temp = 0;
while(1)
{
if(1 == flag)
{
for(i=0; i<strlen(str)/2; i++)
{
temp = str[i];
str[i] = str[strlen(str)-1-i];
str[strlen(str)-1-i] = temp;
}
flag = 0;
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callBack_print,NULL) != 0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,callBack_reaerve,NULL) != 0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
(tid2,NULL);
return 0;
}
引入互斥锁
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t mutex;
int fd_rd;
int fd_cp;
//A线程
void* callBackA(void* arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
off_t size = lseek(fd_rd, 0, SEEK_END);
lseek(fd_rd,0,SEEK_SET);
lseek(fd_cp,0,SEEK_SET);
int i = 0;
char c;
for(i=0; i<size/2; i++)
{
if(read(fd_rd, &c, 1) <= 0)
{
perror("read");
}
write(fd_cp, &c, 1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
//B线程
void* callBackB(void* arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
off_t size = lseek(fd_rd, 0, SEEK_END);
lseek(fd_rd,size/2,SEEK_SET);
lseek(fd_cp,0,SEEK_END);
int i = 0;
char c = 0;
for(i = 0;i < size/2;i++)
{
write(fd_cp,&c,1);
}
for(i=size/2; i<size; i++)
{
if(read(fd_rd, &c, 1) <= 0)
{
perror("read");
}
write(fd_cp, &c, 1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
printf("准备运行程序\n");
//打开原图片
fd_rd = open("./1.png",O_RDONLY);
if(fd_rd < 0)
{
perror("open");
exit(0);
}
//打开要拷贝到的位置文件
fd_cp = open("./copy.png",O_RDWR|O_TRUNC|O_CREAT,07770);
if(fd_cp < 0)
{
perror("open");
exit(0);
}
//创建锁
pthread_mutex_init(&mutex,NULL);
//创建A线程
pthread_t tida;
if(pthread_create(&tida,NULL,callBackA,NULL) != 0)
{
perror("pthread_create");
return -1;
}
//创建B线程
pthread_t tidb;
if(pthread_create(&tidb,NULL,callBackB,NULL) != 0)
{
perror("pthread_create");
return -1;
}
pthread_join(tida,NULL);
pthread_join(tidb,NULL);
close(fd_rd);
close(fd_cp);
//销毁锁
pthread_mutex_destroy(&mutex);
return 0;
}