下面這支程式示範了 POSIX 執行緒最基礎的兩個動作:用 pthread_create 建立新執行緒,再用 pthread_join 等待它結束並取回傳值。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
char message[] = "hello world ";
void *thread_function(void *arg) /* 執行緒函數 */
{
printf("thread_function is running, Argument is %s\n", (char *)arg);
sleep(3);
strcpy(message, "Bye!");
pthread_exit("Thank you for the cpu time"); /* 執行緒退出 */
}
int main()
{
int res;
pthread_t a_thread; /* 新執行緒的識別碼 */
void *thread_result; /* 執行緒回傳值 */
res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
if (res != 0) { /* 建立失敗 */
perror("Thread create error!");
exit(EXIT_FAILURE);
}
printf("waiting for thread to finish...\n");
res = pthread_join(a_thread, &thread_result); /* 等待新執行緒結束 */
if (res != 0) {
perror("Thread join error!");
exit(EXIT_FAILURE);
}
printf("Thread joined, it returned %s\n", (char *)thread_result);
printf("Message is now %s\n", message);
exit(EXIT_SUCCESS);
}
多執行緒程式的編譯要加上重入與 pthread 相關選項:
cc -D_REENTRANT thread.c -g -o thread -lpthread
執行後可以觀察到,全域變數 message 經由建立函數傳給執行緒函數,內容從 hello world 變成了 Bye!。這是因為主執行緒在 pthread_join 處停下等待,新執行緒執行完畢後才繼續往下走;若拿掉 join,主程式可能先結束,message 就未必被改到。
另外注意 pthread_join 的第二個參數:只有新執行緒真的結束,這個呼叫才會回傳並把 pthread_exit 傳出的值填進去,否則主執行緒會一直阻塞。若不希望阻塞,可改用 pthread_detach 讓執行緒自行回收資源。