void*
pthread ライブラリによって呼び出され、pthread ライブラリがメソッドに渡すメソッドを使用する必要があります。これは、最後のパラメーターとしてvoid*
渡すのと同じポインターです。pthread_create
単一の を使用してスレッドに任意のパラメーターを渡す方法の例を次に示しますvoid*
。
struct my_args {
char *name;
int times;
};
struct my_ret {
int len;
int count;
};
void * PrintHello(void *arg) {
my_args *a = (my_args*)arg;
for (int i = 0 ; i != a->times ; i++) {
cout << "Hello " << a->name << endl;
}
my_ret *ret = new my_ret;
ret->len = strlen(a->name);
ret->count = strlen(a->name) * a->times;
// If the start_routine returns, the effect is as if there was
// an implicit call to pthread_exit() using the return value
// of start_routine as the exit status:
return ret;
}
...
my_args a = {"Peter", 5};
pthread_create(&mpthread, NULL, PrintHello, &a);
...
void *res;
pthread_join(mpthread, &res);
my_ret *ret = (my_ret*)(*res);
cout << ret->len << " " << ret->count << endl;
delete ret;
関数が引数を取ったり何かを返したりしたくない場合でも、pthread ライブラリは関数にパラメーターを渡し、その戻り値を収集するため、関数には適切な署名が必要です。void
1 つのパラメーターを受け取る関数の代わりに、パラメーターをとらない関数へのポインターを渡すと、void*
未定義の動作になります。