如何将多个参数传递给C中的线程

时间:2022-03-19 05:49:06

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 ?

我试图将两个参数传递给C中的一个线程。我创建了一个数组(大小为2),并试图将该数组传递给线程。这是将多个参数传递给线程的正确方法吗?

// 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);

2 个解决方案

#1


17  

Since you pass in a void pointer, it can point to anything, including a structure, as per the following example:

由于传入了一个void指针,它可以指向任何东西,包括一个结构,如下例所示:

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.

#2


1  

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.

这是一种方式。另一个常见的方法是将指针传递给结构体。这样,您可以使用不同的“参数”类型,并且参数被命名而不是索引,这有时可以使代码更容易阅读/遵循。

#1


17  

Since you pass in a void pointer, it can point to anything, including a structure, as per the following example:

由于传入了一个void指针,它可以指向任何东西,包括一个结构,如下例所示:

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.

#2


1  

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.

这是一种方式。另一个常见的方法是将指针传递给结构体。这样,您可以使用不同的“参数”类型,并且参数被命名而不是索引,这有时可以使代码更容易阅读/遵循。