c++多線程(1)

C++ 多線程

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

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

  • 線程的多任務處理是同一程序的片斷的併發執行。編程

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

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

本 教程假設您使用的是 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 則說明建立線程失敗。async

終止線程

使用下面的程序,咱們能夠用它來終止一個 POSIX 線程:ide

#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
相關文章
相關標籤/搜索