linux下的C++多線程


原文鏈接:http://blog.csdn.net/lee1054908698/article/details/54633056

本隨筆作為多線程筆記使用,內容完全照搬原博

 

多線程是多任務處理的一種特殊形式,多任務處理允許讓電腦同時運行兩個或兩個以上的程序。一般情況下,兩種類型的多任務處理:基於進程和基於線程。

  • 基於進程的多任務處理是程序的並發執行。

  • 線程的多任務處理是同一程序的片段的並發執行。

多線程程序包含可以同時運行的兩個或多個部分。這樣的程序中的每個部分稱為一個線程,每個線程定義了一個單獨的執行路徑。

C++ 不包含多線程應用程序的任何內置支持。相反,它完全依賴於操作系統來提供此功能。

本教程假設您使用的是 Linux 操作系統,我們要使用 POSIX 編寫多線程 C++ 程序。POSIX Threads 或 Pthreads 提供的 API 可在多種類 Unix POSIX 系統上可用,比如 FreeBSD、NetBSD、GNU/Linux、Mac OS X 和 Solaris。

創建線程

下面的程序,我們可以用它來創建一個 POSIX 線程:

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg) 

 

在這里,pthread_create 創建一個新的線程,並讓它可執行。下面是關於參數的說明:

參數說明

參數 說明
thread 指向線程標識符指針。
attr 一個不透明的屬性對象,可以被用來設置線程屬性。您可以指定線程屬性對象,也可以使用默認值 NULL。
start_routine 線程運行函數起始地址,一旦線程被創建就會執行。
arg 運行函數的參數。它必須通過把引用作為指針強制轉換為 void 類型進行傳遞。如果沒有傳遞參數,則使用 NULL。

創建線程成功時,函數返回 0,若返回值不為 0 則說明創建線程失敗。

終止線程

使用下面的程序,我們可以用它來終止一個 POSIX 線程:

#include <pthread.h>
pthread_exit (status) 

 

在這里,pthread_exit 用於顯式地退出一個線程。通常情況下,pthread_exit() 函數是在線程完成工作后無需繼續存在時被調用。

如果 main() 是在它所創建的線程之前結束,並通過 pthread_exit() 退出,那么其他線程將繼續執行。否則,它們將在 main() 結束時自動被終止。

實例:
以下簡單的實例代碼使用 pthread_create() 函數創建了 5 個線程,每個線程輸出"Hello Runoob!":

#include <iostream>
// 必須的頭文件是
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
// 線程的運行函數,函數返回的是函數指針,便於后面作為參數  
void* say_hello(void* args)
{
    cout << "Hello Runoob!" << 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 Runoob!
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);
}

 

現在編譯並執行程序,將產生下列結果:

$ g++ test.cpp -lpthread -o test.o
$ ./test.o
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);
}

 

當上面的代碼被編譯和執行時,它會產生下列結果:

$ 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

 

連接和分離線程

我們可以使用以下兩個函數來連接或分離線程:

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的訪問和修改順序是正常的,這就達到了多線程的目的了,但是線程的運行順序是混亂的,混亂就是正常?

信號量的實現

信號量是線程同步的另一種實現機制,信號量的操作有signalwait,本例子采用條件信號變量

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

 

C++ 11中的多線程技術

C++11 新標准中引入了四個頭文件來支持多線程編程,他們分別是 <atomic> ,<thread>,<mutex>,<condition_variable><future>

  • <atomic>:提供原子操作功能,該頭文主要聲明了兩個類, std::atomic 和 std::atomic_flag,另外還聲明了一套 C 風格的原子類型和與 C 兼容的原子操作的函數。

  • <thread>:線程模型封裝,該頭文件主要聲明了 std::thread 類,另外 std::this_thread 命名空間也在該頭文件中。

  • <mutex>:互斥量封裝,該頭文件主要聲明了與互斥量(mutex)相關的類,包括 std::mutex 系列類,std::lock_guard, std::unique_lock, 以及其他的類型和函數。

  • <condition_variable>:條件變量,該頭文件主要聲明了與條件變量相關的類,包括 std::condition_variable 和 std::condition_variable_any。

  • <future>:實現了對指定數據提供者提供的數據進行異步訪問的機制。該頭文件主要聲明了 std::promise, std::package_task 兩個 Provider 類,以及 std::future 和 std::shared_future 兩個 Future 類,另外還有一些與之相關的類型和函數,std::async() 函數就聲明在此頭文件中。

簡單示例:

#include <iostream>
#include <thread>
using namespace std;
void thread_1()
{
    cout << "hello from thread_1" << endl;
}
int main(int argc, char **argv)
{
    thread t1(thread_1);
    /**
    join()相當於調用了兩個函數:WaitForSingleObject、CloseHandle,事實上,在vc12中也是這么實現的
    */
    t1.join();
    return 0;
}

 

注意事項

  1. 若線程調用到的函數在一個類中,則必須將該函數聲明為靜態函數函數

因為靜態成員函數屬於靜態全局區,線程可以共享這個區域,故可以各自調用。

    
#include <iostream>  
    #include <pthread.h>  
      
    using namespace std;  
      
    #define NUM_THREADS 5  
      
    class Hello  
    {  
    public:  
        //多線程調用,聲明為static
        static void* say_hello( void* args )  
        {  
            cout << "hello..." << endl;  
        }  
    };  
      
    int main()  
    {  
        pthread_t tids[NUM_THREADS];  
        for( int i = 0; i < NUM_THREADS; ++i )  
        {  
            int ret = pthread_create( &tids[i], NULL, Hello::say_hello, NULL );  
            if( ret != 0 )  
            {  
                cout << "pthread_create error:error_code" << ret << endl;  
            }  
        }  
        pthread_exit( NULL );  
    }  
 
        

測試結果:

    
    hello...  
    hello...  
    hello...  
    hello...  
    hello... 
  1. 代碼中如果沒有pthread_join主線程會很快結束從而使整個進程結束,從而使創建的線程沒有機會開始執行就結束了。加入pthread_join后,主線程會一直等待直到等待的線程結束自己才結束,使創建的線程有機會執行。

  2. 線程創建時屬性參數的設置pthread_attr_t及join功能的使用
    線程的屬性由結構體pthread_attr_t進行管理。

typedef struct
{
    int      detachstate;       //線程的分離狀態
    int      schedpolicy;       //線程調度策略
    struct sched_param   schedparam;   //線程的調度參數
    int inheritsched;       //線程的繼承性 
    int scope;              //線程的作用域 
    size_t guardsize;   //線程棧末尾的警戒緩沖區大小 
    int stackaddr_set; 
    void * stackaddr;   //線程棧的位置 
    size_t stacksize;   // 線程棧的大小
}pthread_attr_t;

 

示例:

    #include <iostream>  
    #include <pthread.h>  
      
    using namespace std;  
      
    #define NUM_THREADS 5  
      
    void* say_hello( void* args )  
    {  
        cout << "hello in thread " << *(( int * )args) << endl;  
        int status = 10 + *(( int * )args); //線程退出時添加退出的信息,status供主程序提取該線程的結束信息  
        pthread_exit( ( void* )status );   
    }  
      
    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功能表示主程序可以等線程結束后再去做某事,實現了主程序和線程同步功能  
        for( int i = 0; i < NUM_THREADS; ++i )  
        {  
            indexes[i] = i;  
            int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) );  
            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;  
        }  
        else  
        {  
            cout << "pthread_join get status:" << (long)status << endl;  
        }  
        }  
    }  

 

測試結果:

hello in thread hello in thread 1hello in thread 3
hello in thread 4
0
hello in thread 2
pthread_join get status:10
pthread_join get status:11
pthread_join get status:12
pthread_join get status:13
pthread_join get status:14


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM