简体   繁体   English

pthread_create中的多个参数

[英]Multiple argument in pthread_create

According to pthread_create man page, the argument of the function is: 根据pthread_create手册页,该函数的参数为​​:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);

regarding the void *arg , I just wonder if I can pass multiple argument to it, because the function that I write requires 2 arguments. 关于void *arg ,我只是想知道是否可以将多个参数传递给它,因为我编写的函数需要2个参数。

With your void* you can pass a struct of your choosing: 使用void*您可以传递您选择的结构:

struct my_args {
  int arg1;
  double arg2;
};

This effectively allows you to pass arbitrary arguments in. Your thread start routine can do nothing other than un-pack those to call the real thread start routine (which could in itself come from that struct). 这有效地允许您传递任意参数。线程启动例程只能进行解压缩以调用实际的线程启动例程(它们本身可能来自该结构),除此之外,什么也不能做。

create a struct and rewrite your function to take only 1 arg and pass both args within the struct. 创建一个结构并重写您的函数以仅使用1个arg并将两个arg传递到该结构中。

instead of 代替

thread_start(int a, int b) {

use 采用

typedef struct ts_args {
   int a;
   int b;
} ts_args;

thread_start(ts_args *args) {

Use a structure and malloc . 使用结构和malloc eg 例如

struct 
{
   int x;
   int y;
   char str[10];
} args;

args_for_thread = malloc(sizeof(args));

args_for_thread->x = 5;

... etc

Then use args_for_thread as the args argument for pthread_create (use a cast from void* to args*). 然后将args_for_thread用作pthread_createargs参数(使用从void *到args *的args_for_thread )。 It is up to that thread to free the memory. 释放内存取决于该线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM