rsc*_*rin 1 c multithreading fork pthreads
有人可以告诉我如何替换这个简单的代码使用pthread_create而不是fork()?有可能吗?特别是,我遇到了传递给main()的struct*ex的一些问题.我怎么改变它?
int k=0;
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
struct primi{
int s;
int temp;};
struct example{
int c;
struct primi primissimi;};
//handler atfork()
void prepare(void){
pthread_mutex_lock(&mutex);}
void parent(void){
pthread_mutex_unlock(&mutex);}
void child(void){
pthread_mutex_unlock(&mutex); }
void *funzione_thread(void* args){
pthread_mutex_lock(&mutex);
struct example *exthread = args;
struct example locale = *exthread;
locale.primissimi.s++;
pthread_mutex_unlock(&mutex);
//do something
pthread_exit(NULL);
}
int ffork(struct example *extmp){
pthread_t id[5];
int i;
while(k<3){
k++;
pthread_create(&id[k],NULL,funzione_thread,extmp);
}
for(i=1;i<=3;i++){
pthread_join( id[i] ,NULL );
printf("waited thread %d\n",i);
}
printf("threads completed\n");
return 1;
}
int main(int argc, char** argv){
struct example *ex = malloc(sizeof(*ex));
int pid,tmp,err;
if ((err = pthread_atfork(prepare, parent, child)) != 0){
printf("can't install fork handlers");
exit(-1);}
pid=fork();
if(pid==0){
ex->c=1;
ex->primissimi.s=1;
if((tmp=ffork(ex))!=1){
printf("error ffork\n");
exit(0);
}
else{printf("ok ffork\n");
pthread_exit (NULL);
}
}
else{
sleep(10);
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)