linux 下常用的建立多線程函數pthread_create(pthread_t * thread , pthread_attr_t * attr , void *(*start_routine)(void*) , void *args);
其中第一個參數用來儲存線程資訊,第二個參數指新線程的運行屬性,可以設定為NULL,第三個參數為自訂的線程函數,第四個參數就是線程函數需要用到的參數,一般如果要傳遞多個參數,可以設定為結構體(struct)類型,這裡我們使用int類型的變數。
下面我著重討論一個用for結構來建立多個線程時參數傳遞的問題:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define th_pop 20 pthread_mutex_t mutex; pthread_t a_thread[th_pop]; void * thread_func(void *args) { pthread_mutex_lock(&mutex); int t_id = *(int*)args; printf("the id of this thread is %d\n",t_id); pthread_mutex_unlock(&mutex); return (void*)NULL; } void init() { pthread_mutex_init(&mutex, NULL); int i; for( i=0; i<th_pop; i++) { pthread_create(&a_thread[i] , NULL , thread_func , &i); } //wait the end of the threads; for( i=0; i<th_pop; i++) { int res = pthread_join(a_thread[i] , NULL); if(res != 0) printf("the thread id: %d ends fail \n",i); } pthread_mutex_destroy(&mutex); } int main() { init(); return 0; }
運行結果:
huangcheng@ubuntu:~$ ./a.outthe id of this thread is 2 the id of this thread is 8 the id of this thread is 9 the id of this thread is 9 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20 the id of this thread is 20