Replace the range () with pthread_create ()

advertisements

Can someone show me how to replace this simple code to use pthread_create instead of fork()? Is it possible?in particular, I've some problems with the struct *ex passed into main(). how have I to change it?

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;
 }


fork() creates an new process,
pthread_create() spawns a new thread, both the functions do drastically different things. A Process and a Thread are different.
Are you sure what you are trying to achieve?