Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

pthreads - How to pass multiple parameters to a thread in C

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...