很久很久以前,我對C語言的了解並不是很多,我最早聽說多線程編程是用Java,其實C語言也有多線程編程,而且更為簡單、方便、強大。下面就讓我們簡單領略一下Unix C語言環境下的多線程編程吧! 下面先看一個簡單的單線程程序: /* 06.3.6 Sghello.c Hello,world -- Single Thread */ #include #define NUM 6 int main() { void print_msg(char*); print_msg("hello,"); print_msg("world!"); } void print_msg(char* m) { int i; for(i=0;i { printf("%s",m); fflush(stdout); sleep(1); } } 下圖反映了程序的執行流程:執行結果: $ ./sghello.exe hello,hello,hello,hello,hello,hello,world!world!world!world!world!world! 那么如果想同時執行兩個對於print_msg函數的調用,就想使用fork建立兩個新的進程一樣,那該怎么辦?這種思想清楚的體現在下圖:
那么怎么才能達到這種效果呢? 我們可以使用函數pthread_create創建一個新的線程。 函數原型: int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*func)(void*), void *arg); 參數: thread 指向pthread_t類型變量的指針 attr 指向pthread_attr_t類型變量的指針,或者為NULL func 指向新線程所運行函數的指針 arg 傳遞給func的參數 返回值 0 成功返回 errcode 錯誤 我們可以使用函數pthread_join等待某進程結束。 函數原型:int pthread_join(pthread_t thread,void ** retval); 參數: thread 所等待的進程 retval 指向某存儲線程返回值的變量 返回值: 0 成功返回 errorcode 錯誤 以上兩個函數都包含在頭文件pthread.h中。 下面請看多線程版的Hello,world! /* 06.3.6 Mhello1.c Hello,world -- Multile Thread */ #include #include #define NUM 6 int main() { void print_msg(void*); pthread_t t1,t2; pthread_create(&t1,NULL,print_msg,(void *)"hello,"); pthread_create(&t2,NULL,print_msg,(void *)"world!\n"); pthread_join(t1,NULL); pthread_join(t2,NULL); } void print_msg(void* m) { char *cp=(char*)m; int i; for(i=0;i { printf("%s",m); fflush(stdout); sleep(1); } } 運行結果:
$ gcc mhello1.c -o mhello1.exe $ ./mhello1.exe hello,world! hello,world! hello,world! hello,world! hello,world! hello,world! C語言有一次拓展了我的視野,多線程的問題還有很多,像線程間的分工合作、使用互斥機制保證線程間數據的安全共享、使用條件變量同步線程間的數據傳輸、傳遞多個參數給線程等,若讀者有興趣,可自行深入。 推薦《Understanding Unix/Linux Programming》