pthread_create不接受参数

问题描述:

我想创建一个pthread,并且对创建它所需的参数感到困惑。pthread_create不接受参数

我想将多个参数传递给pthread的入口函数,并将其封装到结构中。但pthread_create不接受它。

这里是我的代码的相关部分:

Customer_Spawn_Params *params = (Customer_Spawn_Params*) malloc(sizeof(Customer_Spawn_Params)); 
    params->probability = chance; 
    params->queue = queue; 

    pthread_t customer_spawn_t; 
    if (pthread_create(&customer_spawn_t, NULL, enqueue_customers, &params)) { 
    } 

这里是Customer_Spawn_Params结构:

typedef struct { 
     Queue *queue; 
     double probability; 
} Customer_Spawn_Params; 

最后,这里是它接受一个指向Customer_Spawn_Params结构的enqueue_customers()

void *enqueue_customers(Customer_Spawn_Params *params) { 
     int customer_id = 0; 
     double probability = params->probability; 
     Queue *queue = params->queue; 
     while(true) { 
       sleep(1); 
       bool next_customer = next_bool(probability); 
       if (next_customer) { 
         Customer *customer = (Customer*) malloc(sizeof(Customer)); 
         customer->id = customer_id; 
         enqueue(queue, customer); 
         customer_id++; 
       } 
     } 
     return NULL; 
} 
+0

'但是,pthread_create不接受它.'...你是否得出这个结论? – 2014-12-05 09:12:14

+0

当调用'pthread_create'时,您将最后一个参数(参数传递给线程函数)作为指针*传递给指针*。除非你改变你的线程函数,否则你将会有[* undefined behavior *](http://en.wikipedia.org/wiki/Undefined_behavior)。 – 2014-12-05 09:12:33

+0

将您的参数转换为(void *),并且您的线程处理程序应接受void * – dvhh 2014-12-05 09:12:50

1点

if (pthread_create(&customer_spawn_t, NULL, enqueue_customers, &params))

变化

if (pthread_create(&customer_spawn_t, NULL, enqueue_customers, params))

因为,params是一个指针本身。

点2:

此外,

void *enqueue_customers(Customer_Spawn_Params *params) 

应该

void *enqueue_customers(void *params) 

在你的功能,你必须强制转换回实际的指针,例如,

void *enqueue_customers(void *params) 
{ 
    Customer_Spawn_Params *p = params; 
+0

请不要将'void *'强制转换为某种东西。这是完全多余的,可能实际上隐藏了问题。 – 2014-12-05 09:18:21

+0

@JensGustedt好的,先生,谢谢。你能否详细说明或链接到一个有点详细阐述的帖子(可能是一个小例子)? – 2014-12-05 09:19:56

+0

高兴:) https://gustedt.wordpress.com/2014/04/02/dont-use-casts-i/ – 2014-12-05 09:23:40

您的功能enqueue_customers没有正确的原型。它应该是

void *enqueue_customers(void* p) { 
    Customer_Spawn_Params *params = p; 
    ...