2

pthread の hello world の例では、次のように記述されています。

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

void * print_hello(void *arg)
{
  printf("Hello world!\n");
  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t thr;
  if(pthread_create(&thr, NULL, &print_hello, NULL))
  {
    printf("Could not create thread\n");
    return -1;
  }

  if(pthread_join(thr, NULL))
  {
    printf("Could not join thread\n");
    return -1;
  }
  return 0;
}

ご覧print_helloのとおりpthread_create()、引数はありませんが、定義では次のようになりますvoid * print_hello(void *arg)

どういう意味ですか?

今、私はこの実装を持っていると仮定します

void * print_hello(int a, void *);
int main(int argc, char **argv)
{
  pthread_t thr;
  int a = 10;
  if(pthread_create(&thr, NULL, &print_hello(a), NULL))
  {
    printf("Could not create thread\n");
    return -1;
  }
  ....
  return 0;
}
void * print_hello(int a, void *arg)
{
  printf("Hello world and %d!\n", a);
  return NULL;
}

今、私はこのエラーを受け取ります:

too few arguments to function print_hello

それで、どうすればそれを修正できますか?

4

1 に答える 1

4

pthreadタイプの1つの引数void *をスレッド関数に渡します。したがって、関数の4番目の引数として必要な任意のタイプのデータへのポインターを渡すことができpthread_createます。コードを修正する以下の例を見てください。

void * print_hello(void *);
int main(int argc, char **argv)
{
    pthread_t thr;
    int a = 10;
    if(pthread_create(&thr, NULL, &print_hello, (void *)&a))
    {
        printf("Could not create thread\n");
        return -1;
    }
    ....
    return 0;
}

void * print_hello(void *arg)
{
    int a = (int)*arg;
    printf("Hello world and %d!\n", a);
    return NULL;
}
于 2012-10-04T19:53:42.743 に答える