pthread 執行緒函式庫

POSIX標準中支援的執行緒函式庫稱為 pthread,我們可以透過 pthread 結構與 pthread_create() 函數執行某個函數指標,以建立新的執行緒。範例 6 顯示了一個利用 pthread 建立兩個執行緒,分別不斷印出 George 與 Mary 的程式。該程式中總共有三個執行主體,第一個是 print_george()、第二個是 print_mary()、第三個是主程式本身。由於每隔 1 秒印一次 George ,但每隔 0.5 秒就印一次 Mary,因此執行結果會以 George, Mary, George, George,Mary 的形式印出。

範例 6 利用pthread 函式庫建立執行緒的範例

#include <pthread.h>     // 引用 pthread 函式庫
#include <stdio.h>    

void *print_george(void *argu) {    // 每隔一秒鐘印出一次 George 的函數
  while (1) {    
    printf("George\n");    
    sleep(1);    
  }    
  return NULL;    
}    

void *print_mary(void *argu) {     // 每隔一秒鐘印出一次 Mary 的函數
  while (1) {    
    printf("Mary\n");    
    sleep(2);    
  }    
  return NULL;    
}    

int main() {     // 主程式開始
  pthread_t thread1, thread2;     // 宣告兩個執行緒
  pthread_create(&thread1, NULL, &print_george, NULL);    // 執行緒 print_george
  pthread_create(&thread2, NULL, &print_mary, NULL);    // 執行緒 print_mary
  while (1) {     // 主程式每隔一秒鐘
    printf("----------------\n");    // 就印出分隔行
    sleep(1);     // 停止一秒鐘
  }    
  return 0;    
}

執行過程與結果

$ gcc thread.c -o thread

$ ./thread
George
Mary
-------------------------
George
-------------------------
George
Mary
-------------------------
George
-------------------------
…
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License