0

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

测试.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 (*)()’

什么*/&我需要添加/删除以传递foodistribute哪个然后将其传递给线程?

4

3 回答 3

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

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

应该做的伎俩

因为原型是:

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));
于 2012-07-11T02:17:59.720 回答
3

建议的最低更改是:

void *foo(void *unused)
{
    printf("BlahBlahBlah\n");
    return 0;
}

void distribute(void *(*f)(void *))
{
    ...as before...
}

pthread_create()函数需要一个指向一个函数的指针,该函数接受一个void *参数并返回一个void *结果(尽管你还没有遇到那个错误)。因此,通过将其foo()转换为一个接受void *参数并返回void *结果的函数,将指针传递给该类型的函数。而且,就其价值而言,您几乎可以肯定地将foo()其制成一个静态函数,因为您不太可能直接从该文件外部调用它。

于 2012-07-11T02:15:30.857 回答
0

这个页面似乎解释得很好: http: //publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp ?topic=%2Fapis%2Fusers_14.htm ;

IBM 文档通常非常好,当它们出现时请留意那些 ibm 链接;)。

因此,显然您需要一个函数指针,其参数中包含一个 void 指针。尝试

void distribute ( void *( *f )(void *) ) {...}

不过,您可能还需要更改 foo 的定义。有关函数指针,请参阅以下教程:http ://www.cprogramming.com/tutorial/function-pointers.html 。注意:我自己没有测试过,所以不能保证它是否会起作用——但我希望它至少可以为你指明正确的方向;)。

于 2012-07-11T02:28:40.197 回答