#include <stdio.h>
#include <pthread.h>
#include <string.h>
char buf[]="1234567";
int key = 0;
void* callback1(void*arg)
{
while(1)
{
if(key == 0)
{
printf("%s\n",buf);
key=1;
}
}
pthread_exit(NULL);
}
void* callback2(void*arg)
{
int i,j;
char temp;
while(1)
{
if(key == 1)
{
for(i=0,j=strlen(buf)-1;i<j;i++,j--)
{
temp = buf[i];
buf[i]=buf[j];
buf[j] = temp;
}
key=0;
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t A,B;
pthread_create(&A,NULL,callback1,NULL);
pthread_create(&B,NULL,callback2,NULL);
pthread_join(A,NULL);
pthread_join(B,NULL);
return 0;
}
运行结果:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
typedef struct open{
int fd;
int fd2;
off_t size;
}FUN;
void* func(void* arg){
FUN* mode=(FUN*)arg;
lseek(mode->fd,0,SEEK_SET);
lseek(mode->fd2,0,SEEK_SET);
char c;
for(int i=0;i<(mode->size)/2;i++){
read(mode->fd,&c,1);
write(mode->fd2,&c,1);
}
printf("前半部分拷贝完成\n");
pthread_exit(NULL);
return NULL;
}
int main(int argc, const char *argv[])
{
FUN mode;
mode.fd=open("./1.png",O_RDONLY);
if(mode.fd<0){
perror("open");
return -1;
}
mode.fd2=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(mode.fd2<0){
perror("open_fd2");
return -1;
}
mode.size=lseek(mode.fd,0,SEEK_END);
pthread_t tid;
pthread_create(&tid,NULL,func,(void*)&mode);
pthread_join(tid,NULL);
char c;
//lseek(mode.fd,(mode.size)/2,SEEK_SET);
//lseek(mode.fd2,(mode.size)/2,SEEK_SET);
for(int i=(mode.size)/2;i<mode.size;i++){
read(mode.fd,&c,1);
write(mode.fd2,&c,1);
}
printf("全部拷贝完成\n");
return 0;
}