向线程传递参数
这个实例演示了如何通过结构传递多个参数。您可以在线程回调中传递任意的数据类型,因为它指向 void,如下面的实例所示:
实例
#include<iostream>#include<cstdlib>#include<pthread.h>usingnamespacestd; #defineNUM_THREADS 5structthread_data{ int thread_id; char *message;}; void *PrintHello(void *threadarg){ structthread_data *my_data; my_data = (structthread_data *)threadarg; cout << "Thread ID : " << my_data->thread_id ; cout << " Message : " << my_data->message << endl; pthread_exit(NULL);}intmain(){ pthread_tthreads[NUM_THREADS]; structthread_datatd[NUM_THREADS]; intrc; inti; for(i=0; i < NUM_THREADS; i++ ){ cout <<"main() : creating thread, " << i << endl; td[i].thread_id = i; td[i].message = (char*)"This is message"; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]); if(rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } } pthread_exit(NULL);}
当上面的代码被编译和执行时,它会产生下列结果:
$ g++-Wno-write-strings test.cpp -lpthread -o test.o
$ ./test.o
main(): creating thread,0
main(): creating thread,1
Thread ID :0Message:Thisis message
main(): creating thread,Thread ID :21
Message:Thisis message
main(): creating thread,3
Thread ID :2Message:Thisis message
main(): creating thread,4
Thread ID :3Message:Thisis message
Thread ID :4Message:Thisis message