c++ 多線程
多線程是多任務處理的一種特殊形式,多任務處理允許讓電腦同時運行兩個或兩個以上的程序。在一般情況下,有兩種類型的多任務處理:基于進程和基于線程。
基于進程的多任務處理處理的是程序的并發執行。基于線程的多任務處理的是同一程序的片段的并發執行。
多線程程序包含可以同時運行的兩個或多個部分。這樣的程序中的每個部分稱為一個線程,每個線程定義了一個單獨的執行路徑。
c++ 不包含多線程應用程序的任何內置支持。相反,它完全依賴于操作系統來提供此功能。
本教程假設您使用的是 linux 操作系統,我們要使用 posix 編寫多線程 c++ 程序。posix threads 或 pthreads 提供的 api 可在多種類 unix posix 系統上可用,比如 freebsd、netbsd、gnu/linux、mac os x 和 solaris。
1. 創建線程
有下面的例程,我們可以用它來創建一個 posix 線程:
#include <pthread.h> pthread_create (thread, attr, start_routine, arg)
在這里,pthread_create 創建一個新的線程,并讓它可執行。這個例程可在代碼內的任何地方被調用任意次數。下面是關于參數的說明:
參數 | 描述 |
---|---|
thread | 一個不透明的、唯一的標識符,用來標識例程返回的新線程。 |
attr | 一個不透明的屬性對象,可以被用來設置線程屬性。您可以指定線程屬性對象,也可以使用默認值 null。 |
start_routine | c++ 例程,一旦線程被創建就會執行。 |
arg | 一個可能傳遞給 start_routine 的參數。它必須通過把引用作為指針強制轉換為 void 類型進行傳遞。如果沒有傳遞參數,則使用 null。 |
一個進程可以創建的最大線程數是依賴于實現的。線程一旦被創建,就是同等的,而且可以創建其他線程。線程之間沒有隱含層次或依賴。
2. 終止線程
有下面的例程,我們可以用它來終止一個 posix 線程:
#include <pthread.h> pthread_exit (status)
在這里,pthread_exit 用于顯式地退出一個線程。通常情況下,pthread_exit() 例程是在線程完成工作后無需繼續存在時被調用。
如果 main() 是在它所創建的線程之前結束,并通過 pthread_exit() 退出,那么其他線程將繼續執行。否則,它們將在 main() 結束時自動被終止。
3. 實例
這個簡單的實例代碼使用 pthread_create() 例程創建了 5 個線程。每個線程打印一個 "hello world!" 消息,然后調用 pthread_exit() 終止線程。
#include <iostream> // 必須的頭文件是 #include <pthread.h> using namespace std; #define num_threads 5 // 線程的運行函數 void* say_hello(void* args) { cout << "hello w3cschool!" << endl; } 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 w3cschool! hello w3cschool! hello w3cschool! hello w3cschool! hello w3cschool!
以下簡單的實例代碼使用 pthread_create() 函數創建了 5 個線程,并接收傳入的參數。每個線程打印一個 "hello w3cschool!" 消息,并輸出接收的參數,然后調用 pthread_exit() 終止線程。
//文件名:test.cpp #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define num_threads 5 void *printhello(void *threadid) { // 對傳入的參數進行強制類型轉換,由無類型指針變為整形數指針,然后再讀取 int tid = *((int*)threadid); cout << "hello w3cschool!線程 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); }
現在編譯并執行程序,將產生下列結果:
$ 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
向線程傳遞參數
這個實例演示了如何通過結構傳遞多個參數。您可以在線程回調中傳遞任意的數據類型,因為它指向 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); }
當上面的代碼被編譯和執行時,它會產生下列結果:
$ 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
4. 連接和分離線程
有以下兩個例程,我們可以用它們來連接或分離線程:
pthread_join (threadid, status) pthread_detach (threadid)
pthread_join() 子例程阻礙調用例程,直到指定的 threadid 線程終止為止。當創建一個線程時,它的某個屬性會定義它是否是可連接的(joinable)或可分離的(detached)。只有創建時定義為可連接的線程才可以被連接。如果線程創建時被定義為可分離的,則它永遠也不能被連接。
這個實例演示了如何使用 pthread_join() 例程來等待線程的完成。
#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; // 初始化并設置線程為可連接的(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); }
當上面的代碼被編譯和執行時,它會產生下列結果:
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.