pthread_create不接受参数

时间:2014-12-05 09:10:16

标签: c pthreads arguments

我正在尝试创建一个pthread,我对创建它所需的参数感到困惑。

我试图将多个参数传递给pthread的entry函数,并将其封装到struct中。但是,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;

最后,这里是enqueue_customers()接受指向Customer_Spawn_Params struct的指针:

    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;
}

2 个答案:

答案 0 :(得分:2)

您的函数enqueue_customers没有正确的原型。它应该是

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

答案 1 :(得分:2)

第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;