2

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 * dosomething(void *connfd)
{

  // Doing something      

}

In the above example,I am passing connfd value only to the thread 'th'.

Is there any way to pass more than one value so that it can be much useful for me?

One more thing, Can we pass an array as an argument to a thread?

Dinesh
  • 16,014
  • 23
  • 80
  • 122
  • Does this answer your question? [Multiple arguments to function called by pthread\_create()?](https://stackoverflow.com/questions/1352749/multiple-arguments-to-function-called-by-pthread-create) – Henke Nov 29 '20 at 13:04

3 Answers3

7

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2
#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);
 } 
lyxmoo
  • 21
  • 2
1

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.

Paul R
  • 208,748
  • 37
  • 389
  • 560
curiouscat
  • 11
  • 1