1. 程式人生 > 實用技巧 >linux多執行緒學習(1)

linux多執行緒學習(1)

基本函式和關係

pthread_create建立一個子執行緒;

pthread_exit是執行緒函式在終止執行時呼叫,就像程序在執行完畢以後呼叫exit函式一樣;

pthread_join制定了主程序將要等待的子程序,該函式將阻塞主程序執行,直到子程序執行完畢,類似於wait函式。

測試程式碼(參考《Linux程式設計》一書):

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 #include <pthread.h>
 6
7 char message[] = "hello,world!"; 8 void* thread_func(void *arg) 9 { 10 printf("thread function is running. Argument is %s\n",(char*)arg); 11 sleep(3); 12 strcpy(message, "Bye!"); 13 pthread_exit("this is the exit message"); 14 } 15 16 int main(void) 17 { 18 int res; 19 pthread_t tid;
20 void *thread_result; 21 res=pthread_create(&tid,NULL,thread_func,(void*)message); 22 if(res!=0) 23 { 24 perror("Thread create failed"); 25 exit(EXIT_FAILURE); 26 } 27 28 res=pthread_join(tid,&thread_result); 29 if(res!=0) 30 { 31 perror("
Thread join failed"); 32 exit(EXIT_FAILURE); 33 } 34 35 printf("Thread joined, it returned: %s\n",(char*)thread_result); 36 printf("now message is: %s\n",message); 37 exit(EXIT_SUCCESS); 38 }

執行結果為:

主程序在建立子程序以後,通過join等待子程序執行,同時,子程序休眠3秒以後,將傳入的引數修改,並返回了“this is the exit message”。

join函式收到了該返回值,並將其傳遞給了thread_result,最後,顯示全域性變數message被修改了。