gpt4 book ai didi

c - 将参数中的函数指针传递给 pthread_create,(C)

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:37 32 4
gpt4 key购买 nike

这是一个说明我的问题的小例子

测试.c:

#include <stdio.h>
#include <pthread.h>

#define CORES 8

pthread_t threads [ CORES ];
int threadRet [ CORES ];

void foo ()
{
printf ("BlahBlahBlah\n" );
}

void distribute ( void ( *f )() )
{
int i;

for ( i = 0; i < CORES; i++ )
{
threadRet [ i ] = pthread_create ( &threads [ i ], NULL, f, NULL );
}
for ( i = 0; i < CORES; i++ )
{
pthread_join ( threads [ i ], NULL );
}
}

int main ()
{
distribute ( &foo );
return 0;
}

Vim/gcc 输出:

test.c:20|11| warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
/usr/include/pthread.h:225|12| note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)()’

我需要添加/删除什么 */& 以将 foo 传递给 distribute 然后传递它到一个线程?

最佳答案

void *foo (void *x)
{
printf ("BlahBlahBlah\n" );
}

void distribute ( void * (*f)(void *) ) {
/* code */
}

应该可以解决问题

因为原型(prototype)是:

extern int pthread_create (pthread_t *__restrict __newthread,
__const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg) __THROW __nonnull ((1, 3));

关于c - 将参数中的函数指针传递给 pthread_create,(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11424614/

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