C++ 多線程
多線程是多任務(wù)處理的一種特殊形式,多任務(wù)處理允許讓電腦同時運行兩個或兩個以上的程序。一般情況下,兩種類型的多任務(wù)處理:基于進程和基于線程。
基于進程的多任務(wù)處理是程序的并發(fā)執(zhí)行。
基于線程的多任務(wù)處理是同一程序的片段的并發(fā)執(zhí)行。
多線程程序包含可以同時運行的兩個或多個部分。這樣的程序中的每個部分稱為一個線程,每個線程定義了一個單獨的執(zhí)行路徑。
C++ 不包含多線程應(yīng)用程序的任何內(nèi)置支持。相反,它完全依賴于操作系統(tǒng)來提供此功能。
本教程假設(shè)您使用的是 Linux 操作系統(tǒng),我們要使用 POSIX 編寫多線程 C++ 程序。POSIX Threads 或 Pthreads 提供的 API 可在多種類 Unix POSIX 系統(tǒng)上可用,比如 FreeBSD、NetBSD、GNU/Linux、Mac OS X 和 Solaris。
創(chuàng)建線程
下面的程序,我們可以用它來創(chuàng)建一個 POSIX 線程:
#include <pthread.h> pthread_create (thread, attr, start_routine, arg)
在這里,pthread_create 創(chuàng)建一個新的線程,并讓它可執(zhí)行。下面是關(guān)于參數(shù)的說明:
參數(shù) | 描述 |
---|---|
thread | 指向線程標(biāo)識符指針。 |
attr | 一個不透明的屬性對象,可以被用來設(shè)置線程屬性。您可以指定線程屬性對象,也可以使用默認值 NULL。 |
start_routine | 線程運行函數(shù)起始地址,一旦線程被創(chuàng)建就會執(zhí)行。 |
arg | 運行函數(shù)的參數(shù)。它必須通過把引用作為指針強制轉(zhuǎn)換為 void 類型進行傳遞。如果沒有傳遞參數(shù),則使用 NULL。 |
創(chuàng)建線程成功時,函數(shù)返回 0,若返回值不為 0 則說明創(chuàng)建線程失敗。
終止線程
使用下面的程序,我們可以用它來終止一個 POSIX 線程:
#include <pthread.h> pthread_exit (status)
在這里,pthread_exit 用于顯式地退出一個線程。通常情況下,pthread_exit() 函數(shù)是在線程完成工作后無需繼續(xù)存在時被調(diào)用。
如果 main() 是在它所創(chuàng)建的線程之前結(jié)束,并通過 pthread_exit() 退出,那么其他線程將繼續(xù)執(zhí)行。否則,它們將在 main() 結(jié)束時自動被終止。
實例
以下簡單的實例代碼使用 pthread_create() 函數(shù)創(chuàng)建了 5 個線程,每個線程輸出"Hello php!":
#include <iostream> // 必須的頭文件是 #include <pthread.h> using namespace std; #define NUM_THREADS 5 // 線程的運行函數(shù) void* say_hello(void* args) { cout << "Hello php!" << endl; } int main() { // 定義線程的 id 變量,多個變量使用數(shù)組 pthread_t tids[NUM_THREADS]; for(int i = 0; i < NUM_THREADS; ++i) { //參數(shù)依次是:創(chuàng)建的線程id,線程參數(shù),調(diào)用的函數(shù),傳入的函數(shù)參數(shù) int ret = pthread_create(&tids[i], NULL, say_hello, NULL); if (ret != 0) { cout << "pthread_create error: error_code=" << ret << endl; } } //等各個線程退出后,進程才結(jié)束,否則進程強制結(jié)束了,線程可能還沒反應(yīng)過來; pthread_exit(NULL); }
使用 -lpthread 庫編譯下面的程序:
$ g++ test.cpp -lpthread -o test.o
現(xiàn)在,執(zhí)行程序,將產(chǎn)生下列結(jié)果:
$ ./test.o Hello php! Hello php! Hello php! Hello php! Hello php!
以下簡單的實例代碼使用 pthread_create() 函數(shù)創(chuàng)建了 5 個線程,并接收傳入的參數(shù)。每個線程打印一個 "Hello php!" 消息,并輸出接收的參數(shù),然后調(diào)用 pthread_exit() 終止線程。
//文件名:test.cpp #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void *PrintHello(void *threadid) { // 對傳入的參數(shù)進行強制類型轉(zhuǎn)換,由無類型指針變?yōu)檎螖?shù)指針,然后再讀取 int tid = *((int*)threadid); cout << "Hello php! 線程 ID, " << tid << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; int indexes[NUM_THREADS];// 用數(shù)組來保存i的值 int rc; int i; for( i=0; i < NUM_THREADS; i++ ){ cout << "main() : 創(chuàng)建線程, " << i << endl; indexes[i] = i; //先保存i的值 // 傳入的時候必須強制轉(zhuǎn)換為void* 類型,即無類型指針 rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&(indexes[i])); if (rc){ cout << "Error:無法創(chuàng)建線程," << rc << endl; exit(-1); } } pthread_exit(NULL); }
現(xiàn)在編譯并執(zhí)行程序,將產(chǎn)生下列結(jié)果:
$ g++ test.cpp -lpthread -o test.o $ ./test.o main() : 創(chuàng)建線程, 0 main() : 創(chuàng)建線程, 1 main() : 創(chuàng)建線程, 2 main() : 創(chuàng)建線程, 3 main() : 創(chuàng)建線程, 4 Hello php! 線程 ID, 4 Hello php! 線程 ID, 3 Hello php! 線程 ID, 2 Hello php! 線程 ID, 1 Hello php! 線程 ID, 0
向線程傳遞參數(shù)
這個實例演示了如何通過結(jié)構(gòu)傳遞多個參數(shù)。您可以在線程回調(diào)中傳遞任意的數(shù)據(jù)類型,因為它指向 void,如下面的實例所示:
#include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 struct thread_data{ int thread_id; char *message; }; void *PrintHello(void *threadarg) { struct thread_data *my_data; my_data = (struct thread_data *) threadarg; cout << "Thread ID : " << my_data->thread_id ; cout << " Message : " << my_data->message << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; struct thread_data td[NUM_THREADS]; int rc; int i; for( i=0; i < NUM_THREADS; i++ ){ cout <<"main() : creating thread, " << i << endl; td[i].thread_id = i; td[i].message = "This is message"; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]); if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } } pthread_exit(NULL); }
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
$ g++ -Wno-write-strings test.cpp -lpthread -o test.o $ ./test.o main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Thread ID : 3 Message : This is message Thread ID : 2 Message : This is message Thread ID : 0 Message : This is message Thread ID : 1 Message : This is message Thread ID : 4 Message : This is message
連接和分離線程
我們可以使用以下兩個函數(shù)來連接或分離線程:
pthread_join (threadid, status) pthread_detach (threadid)
pthread_join() 子程序阻礙調(diào)用程序,直到指定的 threadid 線程終止為止。當(dāng)創(chuàng)建一個線程時,它的某個屬性會定義它是否是可連接的(joinable)或可分離的(detached)。只有創(chuàng)建時定義為可連接的線程才可以被連接。如果線程創(chuàng)建時被定義為可分離的,則它永遠也不能被連接。
這個實例演示了如何使用 pthread_join() 函數(shù)來等待線程的完成。
#include <iostream> #include <cstdlib> #include <pthread.h> #include <unistd.h> using namespace std; #define NUM_THREADS 5 void *wait(void *t) { int i; long tid; tid = (long)t; sleep(1); cout << "Sleeping in thread " << endl; cout << "Thread with id : " << tid << " ...exiting " << endl; pthread_exit(NULL); } int main () { int rc; int i; pthread_t threads[NUM_THREADS]; pthread_attr_t attr; void *status; // 初始化并設(shè)置線程為可連接的(joinable) pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for( i=0; i < NUM_THREADS; i++ ){ cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, wait, (void *)i ); if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } } // 刪除屬性,并等待其他線程 pthread_attr_destroy(&attr); for( i=0; i < NUM_THREADS; i++ ){ rc = pthread_join(threads[i], &status); if (rc){ cout << "Error:unable to join," << rc << endl; exit(-1); } cout << "Main: completed thread id :" << i ; cout << " exiting with status :" << status << endl; } cout << "Main: program exiting." << endl; pthread_exit(NULL); }
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Sleeping in thread Thread with id : 4 ...exiting Sleeping in thread Thread with id : 3 ...exiting Sleeping in thread Thread with id : 2 ...exiting Sleeping in thread Thread with id : 1 ...exiting Sleeping in thread Thread with id : 0 ...exiting Main: completed thread id :0 exiting with status :0 Main: completed thread id :1 exiting with status :0 Main: completed thread id :2 exiting with status :0 Main: completed thread id :3 exiting with status :0 Main: completed thread id :4 exiting with status :0 Main: program exiting.