2

私は、c++ でコードを pthread として実行するための次の作業コードを見てきました。

void * PrintHello(void * blank) { 
    cout << "Hello World" << endl
}
...
pthread_create(&mpthread, NULL, PrintHello, NULL);

void メソッドの代わりに void * メソッドを使用する必要がある理由と、パラメーターと同じ理由を知りたいです。なぜそれらはポインターである必要があるのですか? また、この void メソッドと void 引数の場合の違いは何ですか?

4

1 に答える 1

1

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 ライブラリは関数にパラメーターを渡し、その戻り値を収集するため、関数には適切な署名が必要です。void1 つのパラメーターを受け取る関数の代わりに、パラメーターをとらない関数へのポインターを渡すと、void*未定義の動作になります。

于 2013-05-24T09:16:04.757 に答える