所以我有一个程序应该有消费者和生产者线程。
在 main 方法中,我想调用 init_consumers()
,它将调用 ptread_init()
这是一些代码:
int init_consumers(char *quantity, pthread_t **cons, void *complex_obj)
{
//seting the limit acording to "quantity"
for (; i < limit; i++)
pthread_create(cons[i], NULL, &consumer, &complex_obj);
return(i);
}
主要
:
#include <pthread.h>
#define MAX_PROD 50
#define MAX_CONS 50
///main entry point of the program
int main(int argc, char *argv[])
{
pthread_t prod[MAX_PROD];
pthread_t cons[MAX_CONS];
struct complex_obj *co;
//some code
co = create_cplx_obj();
//complex object manipulation code
init_producers(argv[2], &prod, co);
init_consumers(argv[3], &cons, co);
//more code
exit(0);
}
argv[2]
和 argv[3]
是用户想要的生产者/消费者数量。
此外,线程签名是:void *producer(void *args);
我仍然遇到 *
和 &
的问题,所以我的问题是在进行方法调用和签名时。
我得到的错误是
n_prod_n_cons.c:158:6: note: expected ‘pthread_t * {aka long unsigned int *}’ but argument is of type ‘pthread_t (*)[50] {aka long unsigned int (*)[50]}’ int init_producers(char *quantity, pthread_t *prod, void *complex_obj)
最佳答案
如我的 comment 中(简洁地)所示,您在 main()
中有 pthread_t
数组;将它们传递给启动器,就像传递一个 int
数组一样。使启动器函数的签名与您传递 int
数组时的操作相匹配。然后使用 &array[index]
将指向数组的单行的指针传递给 pthread_create()
。加起来:
在 main()
中:
init_producers(argv[2], prod, co);
init_consumers(argv[3], cons, co);
(您的代码将 pthread_t (*)[MAX_PROD]
— 指向固定大小的 pthread_t
数组的指针传递给启动器函数,这与签名完全不同它需要一个 pthread_t **
。)
启动器看起来像:
int init_consumers(char *quantity, pthread_t *cons, void *complex_obj)
{
// setting the limit acording to "quantity"
for (; i < limit; i++)
pthread_create(&cons[i], NULL, consumer, &complex_obj);
return(i);
}
cons[i]
是pthread_t
数组中的第i
项;传递它的地址给 pthread_create()
函数它期望的 pthread_t *
。
关于c - 不正确的方法签名和调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023347/