2012年3月18日 星期日

如何用 pthread 來傳值呢

請看這篇網誌


http://pccts.blogspot.com/2007/11/pthreadcreate.html


// You can use the last parameter of pthread_create() to pass arguments
// The following is an example of it.

#include
#include

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指標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;
}

沒有留言:

張貼留言