【发布时间】:2012-02-01 04:36:31
【问题描述】:
谁能告诉我如何替换这个简单的代码来使用 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;
}
【问题讨论】:
-
@BillyONEal 不是真的。我正在开发一个程序,我需要对其进行更改以获得功能。所以我简化了情况
-
行“struct example locale = *exthread;”创建您随后修改的数据的副本,而不是指向现有数据的指针,因此修改不会显示在其他线程中。这是你说的问题吗?如果不是,请解释问题是什么,因为您非常模糊。
-
@tbert 不,问题出在 main 的结构中。我需要将它传递给 pthread_create(xxx,NULL,ffork,here that struct)
-
你在做什么;我真的看不出你有什么问题。具体来说:a) 正在发生但您不希望发生的事情,或 b) 不 正在发生而应该 发生的事情?
标签: c multithreading pthreads fork