Reputation: 14925
I am trying to pass two parameters to a thread in C. I have created an array (of size 2) and am trying to pass that array into the thread. Is this the right approach of passing multiple parameters into a thread ?
// parameters of input. These are two random numbers
int track_no = rand()%15; // getting the track number for the thread
int number = rand()%20 + 1; // this represents the work that needs to be done
int *parameters[2];
parameters[0]=track_no;
parameters[1]=number;
// the thread is created here
pthread_t server_thread;
int server_thread_status;
//somehow pass two parameters into the thread
server_thread_status = pthread_create(&server_thread, NULL, disk_access, parameters);
Upvotes: 13
Views: 49290
Reputation: 881113
Since you pass in a void pointer, it can point to anything, including a structure, as per the following example:
typedef struct s_xyzzy {
int num;
char name[20];
float secret;
} xyzzy;
xyzzy plugh;
plugh.num = 42;
strcpy (plugh.name, "paxdiablo");
plugh.secret = 3.141592653589;
status = pthread_create (&server_thread, NULL, disk_access, &plugh);
// pthread_join down here somewhere to ensure plugh
// stay in scope while server_thread is using it.
Upvotes: 18
Reputation: 206679
That's one way. The other usual one is to pass a pointer to a struct
. This way you can have different "parameter" types, and the parameters are named rather than indexed which can make the code a bit easier to read/follow sometimes.
Upvotes: 1