C語言中的多執行緒
多執行緒是多工處理的一種特殊形式,而多工處理是允許您的計算機同時執行兩個或多個程式的功能。通常,多工處理有兩種型別:基於程序和基於執行緒。
基於程序的多工處理處理程式的併發執行。基於執行緒的多工處理處理同一程式片段的併發執行。
多執行緒程式包含兩個或多個可以併發執行的部分。程式的每個部分都稱為執行緒,每個執行緒定義一個單獨的執行路徑。
C 語言本身並不支援多執行緒應用程式。相反,它完全依賴於作業系統來提供此功能。
本教程假設您正在 Linux 作業系統上工作,我們將使用 POSIX 編寫多執行緒 C 程式。POSIX 執行緒或 Pthreads 提供了可在許多類 Unix POSIX 系統(如 FreeBSD、NetBSD、GNU/Linux、Mac OS X 和 Solaris)上使用的 API。
以下例程用於建立 POSIX 執行緒:
#include <pthread.h> pthread_create (thread, attr, start_routine, arg)
這裡,**pthread_create** 建立一個新執行緒並使其可執行。此例程可以在程式碼中的任何位置呼叫任意次數。以下是引數的描述。
| 引數 | 描述 |
|---|---|
| thread | 子例程返回的新執行緒的不透明唯一識別符號。 |
| attr | 一個不透明的屬性物件,可用於設定執行緒屬性。您可以指定一個執行緒屬性物件,或使用 NULL 表示預設值。 |
| start_routine | 執行緒建立後將執行的 C 例程。 |
| arg | 可以傳遞給 start_routine 的單個引數。它必須作為 void 型別指標的強制轉換透過引用傳遞。如果不需要傳遞引數,則可以使用 NULL。 |
程序可以建立的執行緒的最大數量取決於實現。建立後,執行緒是同級,並且可以建立其他執行緒。執行緒之間沒有隱含的層次結構或依賴關係。
終止執行緒
我們使用以下例程來終止 POSIX 執行緒:
#include <pthread.h> pthread_exit (status)
這裡 **pthread_exit** 用於顯式退出執行緒。通常,線上程完成其工作並且不再需要存在時,會呼叫 pthread_exit() 例程。
如果 main() 在其建立的執行緒之前完成並使用 pthread_exit() 退出,則其他執行緒將繼續執行。否則,當 main() 完成時,它們將被自動終止。
示例程式碼
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
printf("Hello World! Thread ID, %d
", tid);
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
if (rc) {
printf("Error:unable to create thread, %d
", rc);
exit(-1);
}
}
pthread_exit(NULL);
}輸出
$gcc test.cpp -lpthread $./a.out main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Hello World! Thread ID, 0 Hello World! Thread ID, 1 Hello World! Thread ID, 2 Hello World! Thread ID, 3 Hello World! Thread ID, 4
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP