C++ 多線(xiàn)程

2023-01-04 11:33 更新

C++ 多線(xiàn)程

多線(xiàn)程是多任務(wù)處理的一種特殊形式,多任務(wù)處理允許讓電腦同時(shí)運(yùn)行兩個(gè)或兩個(gè)以上的程序。在一般情況下,有兩種類(lèi)型的多任務(wù)處理:基于進(jìn)程和基于線(xiàn)程。

基于進(jìn)程的多任務(wù)處理處理的是程序的并發(fā)執(zhí)行。基于線(xiàn)程的多任務(wù)處理的是同一程序的片段的并發(fā)執(zhí)行。

多線(xiàn)程程序包含可以同時(shí)運(yùn)行的兩個(gè)或多個(gè)部分。這樣的程序中的每個(gè)部分稱(chēng)為一個(gè)線(xiàn)程,每個(gè)線(xiàn)程定義了一個(gè)單獨(dú)的執(zhí)行路徑。

C++ 不包含多線(xiàn)程應(yīng)用程序的任何內(nèi)置支持。相反,它完全依賴(lài)于操作系統(tǒng)來(lái)提供此功能。

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

創(chuàng)建線(xiàn)程

有下面的例程,我們可以用它來(lái)創(chuàng)建一個(gè) POSIX 線(xiàn)程:

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

在這里,pthread_create 創(chuàng)建一個(gè)新的線(xiàn)程,并讓它可執(zhí)行。這個(gè)例程可在代碼內(nèi)的任何地方被調(diào)用任意次數(shù)。下面是關(guān)于參數(shù)的說(shuō)明:

參數(shù) 描述
thread 一個(gè)不透明的、唯一的標(biāo)識(shí)符,用來(lái)標(biāo)識(shí)例程返回的新線(xiàn)程。
attr 一個(gè)不透明的屬性對(duì)象,可以被用來(lái)設(shè)置線(xiàn)程屬性。您可以指定線(xiàn)程屬性對(duì)象,也可以使用默認(rèn)值 NULL。
start_routine C++ 例程,一旦線(xiàn)程被創(chuàng)建就會(huì)執(zhí)行。
arg 一個(gè)可能傳遞給 start_routine 的參數(shù)。它必須通過(guò)把引用作為指針強(qiáng)制轉(zhuǎn)換為 void 類(lèi)型進(jìn)行傳遞。如果沒(méi)有傳遞參數(shù),則使用 NULL。

一個(gè)進(jìn)程可以創(chuàng)建的最大線(xiàn)程數(shù)是依賴(lài)于實(shí)現(xiàn)的。線(xiàn)程一旦被創(chuàng)建,就是同等的,而且可以創(chuàng)建其他線(xiàn)程。線(xiàn)程之間沒(méi)有隱含層次或依賴(lài)。

終止線(xiàn)程

有下面的例程,我們可以用它來(lái)終止一個(gè) POSIX 線(xiàn)程:

#include <pthread.h>
pthread_exit (status) 

在這里,pthread_exit 用于顯式地退出一個(gè)線(xiàn)程。通常情況下,pthread_exit() 例程是在線(xiàn)程完成工作后無(wú)需繼續(xù)存在時(shí)被調(diào)用。

如果 main() 是在它所創(chuàng)建的線(xiàn)程之前結(jié)束,并通過(guò) pthread_exit() 退出,那么其他線(xiàn)程將繼續(xù)執(zhí)行。否則,它們將在 main() 結(jié)束時(shí)自動(dòng)被終止。

實(shí)例

這個(gè)簡(jiǎn)單的實(shí)例代碼使用 pthread_create() 例程創(chuàng)建了 5 個(gè)線(xiàn)程。每個(gè)線(xiàn)程打印一個(gè) "Hello World!" 消息,然后調(diào)用 pthread_exit() 終止線(xiàn)程。

#include <iostream>
// 必須的頭文件是
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

// 線(xiàn)程的運(yùn)行函數(shù)
void* say_hello(void* args)
{
    cout << "Hello w3cschool!" << endl;
}

int main()
{
    // 定義線(xiàn)程的 id 變量,多個(gè)變量使用數(shù)組
    pthread_t tids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; ++i)
    {
        //參數(shù)依次是:創(chuàng)建的線(xiàn)程id,線(xiàn)程參數(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;
        }
    }
    //等各個(gè)線(xiàn)程退出后,進(jìn)程才結(jié)束,否則進(jìn)程強(qiáng)制結(jié)束了,線(xiàn)程可能還沒(méi)反應(yīng)過(guò)來(lái);
    pthread_exit(NULL);
}

使用 -lpthread 庫(kù)編譯下面的程序:

$ g++ test.cpp -lpthread -o test.o

現(xiàn)在,執(zhí)行程序,將產(chǎn)生下列結(jié)果:

$ ./test.o
Hello w3cschool!
Hello w3cschool!
Hello w3cschool!
Hello w3cschool!
Hello w3cschool!

以下簡(jiǎn)單的實(shí)例代碼使用 pthread_create() 函數(shù)創(chuàng)建了 5 個(gè)線(xiàn)程,并接收傳入的參數(shù)。每個(gè)線(xiàn)程打印一個(gè) "Hello w3cschool!" 消息,并輸出接收的參數(shù),然后調(diào)用 pthread_exit() 終止線(xiàn)程。

//文件名:test.cpp

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{  
   // 對(duì)傳入的參數(shù)進(jìn)行強(qiáng)制類(lèi)型轉(zhuǎn)換,由無(wú)類(lèi)型指針變?yōu)檎螖?shù)指針,然后再讀取
   int tid = *((int*)threadid);
   cout << "Hello w3cschool!線(xiàn)程 ID, " << tid << endl;
   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];
   int indexes[NUM_THREADS];// 用數(shù)組來(lái)保存i的值
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){      
      cout << "main() : 創(chuàng)建線(xiàn)程, " << i << endl;
      indexes[i] = i; //先保存i的值
      // 傳入的時(shí)候必須強(qiáng)制轉(zhuǎn)換為void* 類(lèi)型,即無(wú)類(lèi)型指針        
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)&(indexes[i]));
      if (rc){
         cout << "Error:無(wú)法創(chuàng)建線(xiàn)程," << 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)建線(xiàn)程, 0
main() : 創(chuàng)建線(xiàn)程, 1
main() : 創(chuàng)建線(xiàn)程, 2
main() : 創(chuàng)建線(xiàn)程, 3
main() : 創(chuàng)建線(xiàn)程, 4
Hello w3cschool! 線(xiàn)程 ID, 4
Hello w3cschool! 線(xiàn)程 ID, 3
Hello w3cschool! 線(xiàn)程 ID, 2
Hello w3cschool! 線(xiàn)程 ID, 1
Hello w3cschool! 線(xiàn)程 ID, 0

向線(xiàn)程傳遞參數(shù)

這個(gè)實(shí)例演示了如何通過(guò)結(jié)構(gòu)傳遞多個(gè)參數(shù)。您可以在線(xiàn)程回調(diào)中傳遞任意的數(shù)據(jù)類(lèi)型,因?yàn)樗赶?void,如下面的實(shí)例所示:

#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í)行時(shí),它會(huì)產(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

連接和分離線(xiàn)程

有以下兩個(gè)例程,我們可以用它們來(lái)連接或分離線(xiàn)程:

pthread_join (threadid, status) 
pthread_detach (threadid) 

pthread_join() 子例程阻礙調(diào)用例程,直到指定的 threadid 線(xiàn)程終止為止。當(dāng)創(chuàng)建一個(gè)線(xiàn)程時(shí),它的某個(gè)屬性會(huì)定義它是否是可連接的(joinable)或可分離的(detached)。只有創(chuàng)建時(shí)定義為可連接的線(xiàn)程才可以被連接。如果線(xiàn)程創(chuàng)建時(shí)被定義為可分離的,則它永遠(yuǎn)也不能被連接。

這個(gè)實(shí)例演示了如何使用 pthread_join() 例程來(lái)等待線(xiàn)程的完成。

#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è)置線(xiàn)程為可連接的(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);
      }
   }

   // 刪除屬性,并等待其他線(xiàn)程
   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í)行時(shí),它會(huì)產(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.


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)