本文主要講一下C++多線程html
·使用線程能夠把佔據長時間的程序中的任務放到後臺去處理ios
·程序的運行速度可能加快編程
能夠釋放一些珍貴的資源如內存佔用等等。數組
可是多線程是爲了同步完成多項任務,不是爲了提升運行效率,而是爲了提升資源使用效率來提升系統的效率。線程是在同一時間須要完成多項任務的時候實現的。多線程
首先 咱們如今在學校使用的和大賽使用的C++編程軟件通常都是codeblocks(湖南省比賽是的,其餘就不知道了)ide
可是在CodeBlocks中間 咱們是不能直接使用線程的 須要設置一下函數
線程的頭文件與現場建立格式測試
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
在這裏,pthread_create
建立一個新的線程,並讓它可執行。下面是關於參數的說明:ui
參數 | 說明 |
---|---|
thread | 指向線程標識符指針。保存的是線程id |
attr | 一個不透明的屬性對象,能夠被用來設置線程屬性。您能夠指定線程屬性對象,也可使用默認值 NULL。 |
start_routine | 線程運行函數起始地址,即線程函數名。 |
arg | 運行函數的參數。它必須經過把引用做爲指針強制轉換爲 void 類型進行傳遞。若是沒有傳遞參數,則使用 NULL。 |
建立線程成功時,函數返回 0,若返回值不爲 0 則說明建立線程失敗。spa
線程有建立 天然也就有結束
下面介紹一下結束線程的方法:
使用下面的方法 咱們能夠結束線程
#include <pthread.h>
pthread_exit (status);
在這裏,pthread_exit
用於顯式地退出一個線程。一般狀況下,pthread_exit() 函數是在線程完成工做後無需繼續存在時被調用。
注意,main()函數是一個進程,也是可使用上面的函數去結束它的。若是 main() 是在它所建立的線程以前結束,並經過 pthread_exit() 退出,那麼其餘線程將繼續執行。不然,它們將在 main() 結束時自動被終止。
下面以一個實例來講明一下main()函數是否經過 pthread_exit() 退出的不一樣 下面是代碼
#include <iostream> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void* say_hello(void* args) { cout << "Hello Runoob!" << endl; } int main() { pthread_t tids[NUM_THREADS];// 定義線程的 id 變量,多個變量使用數組 for(int i = 0; i < NUM_THREADS; ++i) { //參數依次是:建立的線程id,線程參數,調用的函數,傳入的函數參數 pthread_create(&tids[i], NULL, say_hello, NULL); } //等各個線程退出後,進程才結束,不然進程強制結束了,線程可能還沒反應過來; pthread_exit(NULL);//倆次運行的不一樣之處在於有沒有這一行 }
//有這一行的運行結果 Hello Runoob!Hello Runoob! Hello Runoob! Hello Runoob! Hello Runoob! //上面是一種結果 因爲多個線程之間是同步的 因此輸出結果能夠有多種 下面是我第二次運行的結果 Hello Runoob!Hello Runoob! Hello Runoob! Hello Runoob! Hello Runoob!
//沒有這一行的運行結果 Hello Runoob! //5個線程僅僅只有一個運行完成 其餘4個直接中斷運行 //一樣的 運行結果會有其餘的狀況 下面是我第二次的運行結果 Hello Runoob!Hello Runoob! Hello Runoob! Hello Runoob!
如下簡單的實例代碼使用 pthread_create() 函數建立了 5 個線程,並接收傳入的參數。每一個線程打印一個 "Hello Runoob!" 消息,並輸出接收的參數,而後調用 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 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 main() : 建立線程, 2 main() : 建立線程, 3 main() : 建立線程, 4 Hello Runoob! 線程 ID, 4 Hello Runoob! 線程 ID, 3 Hello Runoob! 線程 ID, 2 Hello Runoob! 線程 ID, 1 Hello Runoob! 線程 ID, 0
這個實例演示瞭如何經過結構傳遞多個參數。您能夠在線程回調中傳遞任意的數據類型,由於它指向 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]); //傳入到參數必須強轉爲void*類型,即無類型指針 if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } } pthread_exit(NULL); }
當上面的代碼被編譯和執行時,它會產生下列結果:
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
咱們可使用如下兩個函數來鏈接或分離線程:
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.
互斥鎖是實現線程同步的一種機制,只要在臨界區先後對資源加鎖就能阻塞其餘進程的訪問。
#include <iostream> #include <pthread.h> using namespace std; #define NUM_THREADS 5 int sum = 0; //定義全局變量,讓全部線程同時寫,這樣就須要鎖機制 pthread_mutex_t sum_mutex; //互斥鎖 void* say_hello( void* args ) { cout << "hello in thread " << *(( int * )args) << endl; pthread_mutex_lock( &sum_mutex ); //先加鎖,再修改sum的值,鎖被佔用就阻塞,直到拿到鎖再修改sum; cout << "before sum is " << sum << " in thread " << *( ( int* )args ) << endl; sum += *( ( int* )args ); cout << "after sum is " << sum << " in thread " << *( ( int* )args ) << endl; pthread_mutex_unlock( &sum_mutex ); //釋放鎖,供其餘線程使用 pthread_exit( 0 ); } int main() { pthread_t tids[NUM_THREADS]; int indexes[NUM_THREADS]; pthread_attr_t attr; //線程屬性結構體,建立線程時加入的參數 pthread_attr_init( &attr ); //初始化 pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是設置你想要指定線程屬性參數,這個參數代表這個線程是能夠join鏈接的,join功能表示主程序能夠等線程結束後再去作某事,實現了主程序和線程同步功能 pthread_mutex_init( &sum_mutex, NULL ); //對鎖進行初始化 for( int i = 0; i < NUM_THREADS; ++i ) { indexes[i] = i; int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) ); //5個進程同時去修改sum if( ret != 0 ) { cout << "pthread_create error:error_code=" << ret << endl; } } pthread_attr_destroy( &attr ); //釋放內存 void *status; for( int i = 0; i < NUM_THREADS; ++i ) { int ret = pthread_join( tids[i], &status ); //主程序join每一個線程後取得每一個線程的退出信息status if( ret != 0 ) { cout << "pthread_join error:error_code=" << ret << endl; } } cout << "finally sum is " << sum << endl; pthread_mutex_destroy( &sum_mutex ); //註銷鎖 }
測試結果:
hello in thread hello in thread 1hello in thread 3 0 hello in thread 2 before sum is 0 in thread 1 hello in thread 4 after sum is 1 in thread 1 before sum is 1 in thread 3 after sum is 4 in thread 3 before sum is 4 in thread 4 after sum is 8 in thread 4 before sum is 8 in thread 0 after sum is 8 in thread 0 before sum is 8 in thread 2 after sum is 10 in thread 2 finally sum is 10
可知,sum的訪問和修改順序是正常的,這就達到了多線程的目的了,可是線程的運行順序是混亂的,混亂就是正常?
信號量是線程同步的另外一種實現機制,信號量的操做有signal
和wait
,本例子採用條件信號變量
pthread_cond_t tasks_cond;
信號量的實現也要給予鎖機制。
#include <iostream> #include <pthread.h> #include <stdio.h> using namespace std; #define BOUNDARY 5 int tasks = 10; pthread_mutex_t tasks_mutex; //互斥鎖 pthread_cond_t tasks_cond; //條件信號變量,處理兩個線程間的條件關係,當task>5,hello2處理,反之hello1處理,直到task減爲0 void* say_hello2( void* args ) { pthread_t pid = pthread_self(); //獲取當前線程id cout << "[" << pid << "] hello in thread " << *( ( int* )args ) << endl; bool is_signaled = false; //sign while(1) { pthread_mutex_lock( &tasks_mutex ); //加鎖 if( tasks > BOUNDARY ) { cout << "[" << pid << "] take task: " << tasks << " in thread " << *( (int*)args ) << endl; --tasks; //modify } else if( !is_signaled ) { cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl; pthread_cond_signal( &tasks_cond ); //signal:向hello1發送信號,代表已經>5 is_signaled = true; //代表信號已發送,退出此線程 } pthread_mutex_unlock( &tasks_mutex ); //解鎖 if( tasks == 0 ) break; } } void* say_hello1( void* args ) { pthread_t pid = pthread_self(); //獲取當前線程id cout << "[" << pid << "] hello in thread " << *( ( int* )args ) << endl; while(1) { pthread_mutex_lock( &tasks_mutex ); //加鎖 if( tasks > BOUNDARY ) { cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl; pthread_cond_wait( &tasks_cond, &tasks_mutex ); //wait:等待信號量生效,接收到信號,向hello2發出信號,跳出wait,執行後續 } else { cout << "[" << pid << "] take task: " << tasks << " in thread " << *( (int*)args ) << endl; --tasks; } pthread_mutex_unlock( &tasks_mutex ); //解鎖 if( tasks == 0 ) break; } } int main() { pthread_attr_t attr; //線程屬性結構體,建立線程時加入的參數 pthread_attr_init( &attr ); //初始化 pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是設置你想要指定線程屬性參數,這個參數代表這個線程是能夠join鏈接的,join功能表示主程序能夠等線程結束後再去作某事,實現了主程序和線程同步功能 pthread_cond_init( &tasks_cond, NULL ); //初始化條件信號量 pthread_mutex_init( &tasks_mutex, NULL ); //初始化互斥量 pthread_t tid1, tid2; //保存兩個線程id int index1 = 1; int ret = pthread_create( &tid1, &attr, say_hello1, ( void* )&index1 ); if( ret != 0 ) { cout << "pthread_create error:error_code=" << ret << endl; } int index2 = 2; ret = pthread_create( &tid2, &attr, say_hello2, ( void* )&index2 ); if( ret != 0 ) { cout << "pthread_create error:error_code=" << ret << endl; } pthread_join( tid1, NULL ); //鏈接兩個線程 pthread_join( tid2, NULL ); pthread_attr_destroy( &attr ); //釋放內存 pthread_mutex_destroy( &tasks_mutex ); //註銷鎖 pthread_cond_destroy( &tasks_cond ); //正常退出 }
測試結果:
先在線程2中執行say_hello2,再跳轉到線程1中執行say_hello1,直到tasks減到0爲止。
[2] hello in thread 1 [2] pthread_cond_signal in thread 1 [3] hello in thread 2 [3] take task: 10 in thread 2 [3] take task: 9 in thread 2 [3] take task: 8 in thread 2 [3] take task: 7 in thread 2 [3] take task: 6 in thread 2 [3] pthread_cond_signal in thread 2 [2] take task: 5 in thread 1 [2] take task: 4 in thread 1 [2] take task: 3 in thread 1 [2] take task: 2 in thread 1 [2] take task: 1 in thread 1
初學多線程 這個文章中間的線程參數傳遞存在問題 每一次運行存在參數中有int行的數據
程序就會boom boom boom
可是我不知道是爲何
但願各位大佬能夠告訴我爲何 或者是大家電腦上面沒有問題0.0
多線程的同步機制 因此有一些運行結果不是同樣也不用在乎 你多運行幾回 說不定就有一次的運行結果和個人是同樣的了
此文轉+改,http://www.cnblogs.com/quincyhu/p/5884361.html