使用 Pthreads API 的多執行緒
Pthreads 指的是 POSIX 標準 (IEEE 1003.1c),它定義了用於執行緒建立和同步的 API,這是一個執行緒行為規範,而不是實現。作業系統設計人員可以根據需要以任何方式實現此規範。下面顯示的 C 程式演示了用於構建多執行緒程式的基本 Pthreads API,該程式在單獨的執行緒中計算非負整數的總和。單獨的執行緒在 Pthreads 程式中的指定函式中開始執行。在下面的程式中,這是 runner() 函式。程式開始時,一個單執行緒控制在 main() 中開始。main() 建立一個第二個執行緒,該執行緒在一些初始化後在 runner() 函式中開始控制。這兩個執行緒共享全域性資料 sum。所有 Pthreads 程式都必須包含 pthread.h 標頭檔案。我們將建立的執行緒的識別符號。每個執行緒中都有一組屬性,包括堆疊大小和排程資訊。執行緒的屬性由 pthread_attr_t attr 的宣告表示。我們在函式呼叫 pthread_attr_init(&attr) 中設定屬性。因為我們沒有顯式設定任何屬性,所以我們使用提供的預設屬性。透過 pthread_create() 函式呼叫,建立單獨的執行緒。傳遞執行緒識別符號和執行緒的屬性,我們還傳遞 runner() 函式,新執行緒將在其中開始執行。最後,我們傳遞命令列上提供的整數引數,argv[1]。此時,程式有兩個執行緒:main() 中的初始(或父)執行緒和在 runner() 函式中執行求和操作的求和(或子)執行緒。此程式遵循 fork-join 策略:在建立求和執行緒後,父執行緒將透過呼叫 pthread_join() 函式等待它終止。當它呼叫函式 pthread_exit() 時,求和執行緒將終止。一旦求和執行緒返回,父執行緒將輸出共享資料 sum 的值。
使用 Pthreads API 的多執行緒 C 程式
示例
#include<pthread.h>
#include<stdio.h>
int sum;
/* This ‘sum’ is shared by the thread(s) */
void *runner(void *param);
/* threads call this function */
int main(int argc, char *argv[]){
pthread t tid;
/* the thread identifier */
pthread attr t attr;
/* set of thread attributes */
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 begin handle 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);
}
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP