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
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
.
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.
#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);
}