How to pass more than one value as an argument to a thread in C?

前端 未结 3 2005
梦如初夏
梦如初夏 2021-01-21 13:10

In C, how can i pass more than one argument to a thread?

Normally, I do it in a way like,

 pthread_create(&th,NULL,dosomething,(void*)connfd);


void         


        
相关标签:
3条回答
  • 2021-01-21 13:17

    Pack the several values inside a struct on the heap (so malloc it and fill it before), then call pthread_create with a pointer to that struct.

    0 讨论(0)
  • 2021-01-21 13:25

    About passing an array as an argument, of course you can do that. If you declare an array as,

    int a[3] = {1,2,2};
    

    a is like a label to the starting address of the array. Thus a represents a pointer. *a is equal to a[0] and *(a+1) is equal to a[1]. So you can pass the array to the thread as below:

    pthread_create(&th,NULL,dosomething,(void *)a);
    

    Inside the thread you can cast a back to an int * and use as an array.

    0 讨论(0)
  • 2021-01-21 13:26
    #include <stdio.h> 
    #include <stdlib.h>
    #include <pthread.h> 
    
    void *genSimpleCurList(void *pnum) {
       void  *retval;
    
       int i,j;
    
       j = 0;
    
        // when ptread_create , how to pass a parameters such as integer arrary to pthread
    
       while(j<10) {
         i =*((int *)pnum)+j;
         fprintf(stderr,"pthread creat with parameter is %d\n",i);
         j++;
        } 
    
      return(retval);
    
     }
    
     int  main() {
    
     int i, *j;
     pthread_t idxtid;
     pthread_attr_t attr;
     pthread_attr_init (&attr);
     pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
    
     j = (int *) calloc (1024, sizeof (int));
      for (i = 0; i < 1024; i++) j[i] = i;
    
      rcode = pthread_create (&idxtid, &attr, genSimpleCurList, (void *)j);
    
      exit(0);
     } 
    
    0 讨论(0)
提交回复
热议问题