多線程是多任務處理的一種特殊形式,多任務處理允許讓電腦同時運行兩個或兩個以上的程序。一般情況下,兩種類型的多任務處理:基於進程和基於線程。
基於進程的多任務處理是程序的併發執行。
基於線程的多任務處理是同一程序的片段的併發執行。
多線程程序包含可以同時運行的兩個或多個部分。這樣的程序中的每個部分稱爲一個線程,每個線程定義了一個單獨的執行路徑。
下面的程序,我們可以用它來創建一個 POSIX 線程:
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
創建線程成功時,函數返回 0,若返回值不爲 0 則說明創建線程失敗。
使用下面的程序,我們可以用它來終止一個 POSIX 線程:
#include <pthread.h>
pthread_exit (status)
實例
#include <iostream>
// 必須的頭文件
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
// 線程的運行函數
void* say_hello(void* args)
{
cout << "Hello Runoob!" << endl;
return 0;
}
int main()
{
// 定義線程的 id 變量,多個變量使用數組
pthread_t tids[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; ++i)
{
//參數依次是:創建的線程id,線程參數,調用的函數,傳入的函數參數
int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
if (ret != 0)
{
cout << "pthread_create error: error_code=" << ret << endl;
}
}
//等各個線程退出後,進程才結束,否則進程強制結束了,線程可能還沒反應過來;
pthread_exit(NULL);
}
使用 -lpthread 庫編譯下面的程序:
g++ test.cpp -lpthread -o test.o
執行程序,將產生下列結果:
$ ./test.o
Hello Runoob!
Hello Runoob!
Hello Runoob!
Hello Runoob!
Hello Runoob!
以下簡單的實例代碼使用 pthread_create() 函數創建了 5 個線程,並接收傳入的參數。每個線程打印一個 “Hello Runoob!” 消息,並輸出接收的參數,然後調用 pthread_exit() 終止線程。
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
// 對傳入的參數進行強制類型轉換,由無類型指針變爲整形數指針,然後再讀取
int tid = *((int*)threadid);
cout << "Hello Runoob! 線程 ID, " << tid << endl;
pthread_exit(NULL);
}
int main ()
{
pthread_t threads[NUM_THREADS];
int indexes[NUM_THREADS];// 用數組來保存i的值
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "main() : 創建線程, " << i << endl;
indexes[i] = i; //先保存i的值
// 傳入的時候必須強制轉換爲void* 類型,即無類型指針
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)&(indexes[i]));
if (rc){
cout << "Error:無法創建線程," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
結果如下
main() : 創建線程, 0
main() : 創建線程, 1
Hello Runoob! 線程 ID, 0
main() : 創建線程, Hello Runoob! 線程 ID, 21
main() : 創建線程, 3
Hello Runoob! 線程 ID, 2
main() : 創建線程, 4
Hello Runoob! 線程 ID, 3
Hello Runoob! 線程 ID, 4