gpt4 book ai didi

c - pthread_create 不接受参数

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:26 25 4
gpt4 key购买 nike

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

我试图将多个参数传递给 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;

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

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

最佳答案

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

关于c - pthread_create 不接受参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27312332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com