1、结构体传参
#include <hand.h>
#include <pthread.h>
#include <string.h>
struct dd
{
pthread_mutex_t mutex;
FILE* fp;
FILE* fw;
long size;
};
void * callback1(void* arg)
{
struct dd *p=(struct dd*)arg;
char c;
pthread_mutex_lock(&p->mutex);
fseek(p->fp,0,SEEK_SET);
fseek(p->fw,0,SEEK_SET);
for(int i=0;i<p->size/2;i++)
{
fread(&c,1,1,p->fp);
fwrite(&c,1,1,p->fw);
}
pthread_mutex_unlock(&p->mutex);
pthread_exit(NULL);
}
void * callback2(void* arg)
{
char c;
struct dd *p=(struct dd*)arg;
pthread_mutex_lock(&p->mutex);
fseek(p->fp,p->size/2,SEEK_SET);
fseek(p->fw,p->size/2,SEEK_SET);
for(int i=p->size/2;i<p->size;i++)
{
fread(&c,1,1,p->fp);
fwrite(&c,1,1,p->fw);
}
pthread_mutex_unlock(&p->mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
FILE* f=fopen("1.png","w");
if(NULL==f)
{
perror("fopen");
return -1;
}
fclose(f);
struct dd msg;
msg.fp=fopen("./image.png","r");
if(NULL==msg.fp)
{
perror("fopen");
return -1;
}
msg.fw=fopen("1.png","r+");
if(NULL==msg.fw)
{
perror("fopen");
return -1;
}
fseek(msg.fp,0,SEEK_END);
msg.size=ftell(msg.fp);
pthread_mutex_init(&msg.mutex,NULL);
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callback1,&msg)!=0)
{
printf("pthread_creat failed __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callback2,&msg)!=0)
{
printf("pthread_creat failed __%d__\n",__LINE__);
return -1;
}
// pthread_detach(tid2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&msg.mutex);
fclose(msg.fp);
fclose(msg.fw);
return 0;
}
2、
#include <hand.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
struct dd{
sem_t sem1;
sem_t sem2;
} msg;
char buf[]="1234567";
void * callback1(void* arg)
{
struct dd* p=arg;
char temp;
int i=0;
while(1)
{
if(sem_wait(&p->sem1)<0)
{
perror("P操作");
return NULL;
}
for(int i=0,j=strlen(buf)-1;i<strlen(buf)/2;i++,j--)
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}
//printf("this is tid1 func:%s\n",buf);
if(sem_post(&p->sem2)<0)
{
perror("V操作");
return NULL;
}
}
pthread_exit(NULL);
}
void * callback2(void* arg)
{
struct dd* p=arg;
int i=0;
while(1)
{
if(sem_wait(&p->sem2)<0)
{
perror("P操作");
return NULL;
}
printf("%s\n",buf);
if(sem_post(&p->sem1)<0)
{
perror("V操作");
return NULL;
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&msg.sem1,0,1)<0)
{
perror("semaphore");
return -1;
}
if(sem_init(&msg.sem2,0,0)<0)
{
perror("semaphore");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callback1,&msg)!=0)
{
printf("pthread_creat failed __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callback2,&msg)!=0)
{
printf("pthread_creat failed __%d__\n",__LINE__);
return -1;
}
//pthread_detach(tid2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&msg.sem1);
sem_destroy(&msg.sem2);
return 0;
}