-1

私はCでマルチスレッドプログラミングを学び、基本的なプログラムを理解しようとしています。ランナー関数を理解できませんでした。なぜ、void型へのポインターを返し、voidへのポインターでもあるパラメーターを渡すのですか。また、mainのパラメータがわかりませんでした。

int sum; / this data is shared by the thread(s) 
void *runner(void *param); / the thread 
int main(int argc, char *argv[])
{
 pthread_t tid; / the thread identifier /
 pthread.attr_t attr; / set of thread attributes /
if (argc != 2) {
fprintf(stderr,"usage: a.out <integer value>\n");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr,"%d must be >= 0\n",atoi(argv[1]));
return -1;
/ get the default attributes /
pthread.attr.init (&attr) ;
/ create the thread /
pthread^create(&tid,&attr,runner,argv[1]);
/ wait for the thread to exit /
pthread_join (tid, NULL) ;
printf("sum = %d\n",sum);
/ The thread will begin control in this function /
void *runner(void *param)
{<br />
int i, upper = atoi(param);
sum = 0;<br />
for (i = 1; i <= upper; i
sum += i;
pthread_exit (0) ;
4

1 に答える 1

1

最初のパラメーターmainargcプログラム名を含むコマンド ライン パラメータの数です。argvパラメーター自体である、ゼロで区切られた文字列へのポインターの配列です。したがって、次のようにコマンドラインからプログラムを実行すると:

myprog x y z

次にargc4 にargvなり、次のようになります。

argv[0]: "myprog"
argv[1]: "x"
argv[2]: "y"
argv[3]: "z"
argv[4]: ""

最後の要素は空の文字列にする必要があります。最初の要素 (プログラム名) の正確な形式は、オペレーティング システムと、プログラムが呼び出される正確な方法によって異なります。

関数は、一般にcallbackrunnerとして知られる関数の一種です。他の人 (pthread ライブラリ) によって呼び出されます。他の誰かがあなたの関数を呼び出すためには、それが戻り値の型とパラメーターであることを知る必要があるため、これらは使用されていない場合でも固定されています。

したがって、実際にはどちらも使用しない場合でも(型指定されていないポインター)runnerを返し、パラメーターを受け取る必要があります ( を返すことができます)。これは、pthread ライブラリが期待しているためです。void *void *NULL

于 2013-01-31T17:32:59.250 に答える