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

Ash*_*wal 12 c posix pthreads

我试图将两个参数传递给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);
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 18

由于传入了一个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.
Run Code Online (Sandbox Code Playgroud)

  • 当然,在上面示例中所示的代码中,您必须确保在线程尝试取消引用给定的opinter时不破坏该结构. (4认同)