繁体   English   中英

由于无效指针和整数转换错误,pthread_create无法正常工作

[英]pthread_create does not work due to void pointer and integer conversion error

您如何/为什么要转换为空指针或int?

以下代码错误地生成了编译器错误:

while(num_producers > 0) {
    pthread_t tid; // id of pthread (not used except to call pthread_create)
    pthread_attr_t attr; // pthread attributes (not used except to call pthread_create)
    pthread_attr_init(&attr); // default pthread attributes
    pthread_create(&tid, &attr, producer, num_producers);
    num_producers--;
}

出现以下错误(全部在pthread_create行上):

error: invalid conversion from 'void (*)(int)' to 'void* (*)(void*)'
  error: initializing argument 3 of 'int pthread_create(_opaque_pthread)t**, const pthread_attr_t*, void* (*)(void*), void*)'
  error: invalid conversion from 'int' to 'void*'
  error: initializing argument 4 of 'int pthread_create(_opaque_pthread_t**, const pthread_attr_t*, void* (*)(void*), void*)'

我想创建一个运行(仅)函数“生产者”的pthread,该函数也包含在与main相同的文件中。 为什么不起作用?

以正确的方式声明producer

void * producer(void * p)
{
    intptr_t n = (intptr_t)(p);

    // ... use "n"

}

然后:

int n = 42;

int res = pthread_create(&tid, &attr, producer, (void*)(n));

暂无
暂无

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

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