POSIX 執行緒庫


Pthreads 是指定義一個執行緒建立和同步 API 的 POSIX 標準(IEEE 1003.1c)。這定義了執行緒行為的規範,而不是實現。該規範可以由 OS 設計人員以他們希望的任何方式實現。因此,許多系統都實現了 Pthreads 規範;其中大多數是 UNIX 型別系統,包括 Linux、Mac OS X 和 Solaris。儘管 Windows 本機不支援 Pthreads,但有一些適用於 Windows 的第三方實現。圖 4.9 中顯示的 C 程式演示了用於構建多執行緒程式的基本 Pthreads API,該程式計算單獨執行緒中的非負整數的總和。在 Pthreads 程式中,單獨的執行緒從指定函式開始執行。在下方的程式中,這是 runner() 函式。當這個程式開始時,一個單執行緒控制從 main() 開始。然後,main() 建立一個第二個執行緒,該執行緒在 runner() 函式中開始控制,在進行一些初始化之後。兩個執行緒共用全域性資料 sum。

示例

#include<pthread.h>
#include<stdio.h>
int sum;
/* this sum data is shared by the thread(s) */
/* threads call this function */
void *runner(void *param);
int main(int argc, char *argv[]){
   pthread t tid; /* the thread identifier */
   /* set of thread attributes */
   pthread attr t attr;
   if (argc != 2){
      fprintf(stderr,"usage: a.out 
");       return -1;    }    if (atoi(argv[1]) < 0){       fprintf(stderr,"%d must be >= 0
",atoi(argv[1]));       return -1;    }    /* get the default attributes */    pthread attr init(&attr); /* create the thread */    pthread create(&tid,&attr,runner,argv[1]);    /* wait for the thread to exit */    pthread join(tid,NULL);    printf("sum = %d
",sum); } /* The thread will now begin control in this function */ void *runner(void *param){    int i, upper = atoi(param);    sum = 0;    for (i = 1; i <= upper; i++)       sum += i;    pthread exit(0); }

使用 Pthreads API 的多執行緒 C 程式。

更新於: 2019-10-17

867 瀏覽

啟動你的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.