#include <myhead.h>
char buf[]="abcdefg";
sem_t sem;
void* callback1(void* arg)
{
while(1){
if(sem_wait(&sem)<0){
perror("sem_wait");
pthread_exit(NULL);
}
printf("%s\n",buf);
if(sem_post(&sem)<0){
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
void* callback2(void* arg)
{
int i=0,j=0;
char temp;
while(1){
if(sem_wait(&sem)<0){
perror("sem_wait");
pthread_exit(NULL);
}
for(int i=0,j=strlen(buf)-1;i<j;i++,j--){
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
if(sem_post(&sem)<0){
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem,0,1)){
perror("sem_init");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callback1,NULL)){
fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callback2,NULL)){
fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem);
return 0;
}
创建线程实现对图片的拷贝
#include <myhead.h>
void* callback1(void* arg)
{
int fd_r = open("./1.png", O_RDONLY);
int fd_w = open("./1cpy.png",O_WRONLY | O_CREAT | O_TRUNC,0664);
off_t size = lseek(fd_r,0,SEEK_END);
pthread_mutex_lock((pthread_mutex_t*)arg);
lseek(fd_r,0,SEEK_SET);
lseek(fd_w,0,SEEK_SET);
char c;
for(int i=0; i<size/2;i++){
read(fd_r,&c,1);
write(fd_w,&c,1);
}
pthread_mutex_unlock((pthread_mutex_t*)arg);
printf("前半拷贝完毕\n");
close(fd_r);
close(fd_w);
pthread_exit(NULL);
}
void* callback2(void* arg)
{
int fd_r = open("./1.png", O_RDONLY);
int fd_w = open("./2cpy.png",O_WRONLY | O_CREAT | O_TRUNC,0664);
off_t size = lseek(fd_r,0,SEEK_END);
pthread_mutex_lock((pthread_mutex_t*)arg);
lseek(fd_r,size/2,SEEK_SET);
lseek(fd_w,size/2,SEEK_SET);
char c;
for(int i=size/2; i<size;i++){
read(fd_r,&c,1);
write(fd_w,&c,1);
}
pthread_mutex_unlock((pthread_mutex_t*)arg);
printf("后半拷贝完毕\n");
close(fd_r);
close(fd_w);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
pthread_mutex_t mutex;
pthread_mutex_init(&mutex,NULL);
if(pthread_create(&tid1,NULL,callback1,(void*)&mutex) != 0){
printf("pth1 ok %d\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callback2,(void*)&mutex) != 0){
printf("pth2 ok %d\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}