0

これは私の問題を説明する最小限の例です

test.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 に答える