linux~pthread_create()傳遞引數

2009-04-15 5:25 am
請問pthread_create() 如何傳遞參數?

回答 (1)

2009-04-15 3:58 pm
✔ 最佳答案
// You can use the last parameter of pthread_create() to pass arguments
// The following is an example of it.

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

void *thread_function(void *);

int main() {
pthread_t thread_id[3];
int i,id[3];

for (i=0; i<3; i++) {
id[i] = i;
pthread_create( &thread_id[i], NULL, thread_function, &id[i] );
}

for (i=0; i<3; i++) {
pthread_join( thread_id[i], NULL);
}
}

void *thread_function( void *arg )
{
int id = *((int *) arg);
int i;

if ( id == 0 ) {
printf("I am 0\n");
} else if ( id == 1 ) {
printf("I am 1\n");
} else {
printf("I am 2\n");
}
return arg;
}


收錄日期: 2021-04-30 13:10:21
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090414000016KK09401

檢視 Wayback Machine 備份