Linux 线程传递参数
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <pthread.h> 4 #include <unistd.h> 5 6 #define NUM_THREADS 8 7 8 void *PrintHello(void *args) 9 { 10 int thread_arg; 11 sleep(1); 12 thread_arg = (int)(*((int*)args)); 13 printf("Hello from thread %d\n", thread_arg); 14 return NULL; 15 } 16 17 int main(void) 18 { 19 int rc,t; 20 pthread_t thread[NUM_THREADS]; 21 22 for( t = 0; t < NUM_THREADS; t++) 23 { 24 printf("Creating thread %d\n", t); 25 rc = pthread_create(&thread[t], NULL, PrintHello, &t); 26 if (rc) 27 { 28 printf("ERROR; return code is %d\n", rc); 29 return EXIT_FAILURE; 30 } 31 } 32 sleep(5); 33 for( t = 0; t < NUM_THREADS; t++) 34 pthread_join(thread[t], NULL); 35 return EXIT_SUCCESS; 36 }