pthread_create 是你第一個要用的 pthread API,下列是我們的範例程式
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
/*
* 在 thread_1 裡面執行一個無窮迴圈,並不斷印出 thread_1 訊息
* 為了避免不斷的 loop,我們用 sleep function 在每次迴圈停 1 秒
*/
void *thread_1(void *argv) {
while(1) {
sleep(1);
printf("I am thread_1\n");
}
}
/*
* 基本上和 thread_2 相同,但時間停留 2 秒
*/
void *thread_2(void *argv) {
while (1) {
sleep(2);
printf("I am thread_2\n");
}
}
int main() {
pthread_t t1, t2; // 先宣告兩個 pthread 的變數
// 之後開始建立並執行這兩個 thread,這兩個 thread 分別執行上面 thread_1, thread_2 這兩個 function
pthread_create(&t1, NULL, &thread_1, NULL);
pthread_create(&t2, NULL, &thread_2, NULL);
// 而我們自己的 main thread 也同樣執行無窮迴圈,每次停留三秒
while (1) {
sleep(3);
printf("I am main thread\n");
}
return 0;
}
結果在這邊
> ./pthread-example
I am thread_1
I am thread_2
I am thread_1
I am main thread
I am thread_1
I am thread_1
I am thread_2
I am thread_1
I am main thread
I am thread_2
I am thread_1
I am thread_1
I am thread_2
I am thread_1
I am main thread
I am thread_1
I am thread_2
I am thread_1
我們可以注意到,在撰寫 multi-thread 程式時,需要改變以往 Sequential 的思維,實際上在 multi-thread 的觀念中,所有的 thread 都是同時在執行的 (實際上可能不是啦,但我們在比較高階的角度來看,就當作是同時在進行)。
另外,可以發現雖然 thread_1 停一秒,thread_2 停兩秒,main thread 停三秒,但實際在印出來時還是有先後順序之分,而且每一次都不太固定,這也是 thread 有時候比較抽象的地方。
最後,main thread 是不能停止的,這也是為什麼我們要在 main function 也插入無窮迴圈,因為 main thread 如果直接 return 停止,連帶的會把 thread_1 和 thread_2 一起停止。
thread_create manual: http://man7.org/linux/man-pages/man3/pthread_create.3.html
source code on github: https://github.com/jackzzjack/blogger.git
可以下載 source code 並直接執行 make simple,則會編譯出 pthread-example,之後直接 ./pthread-example 直行即可。
學到了,感謝
回覆刪除