1.3.08_C++ 多線程

多線程是多任務(wù)處理的一種特殊形式,多任務(wù)處理允許讓電腦同時(shí)運(yùn)行兩個(gè)或兩個(gè)以上的程序。

一般情況下,兩種類型的多任務(wù)處理:基于進(jìn)程和基于線程。

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

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

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

創(chuàng)建線程

下面的程序,我們可以用它來創(chuàng)建一個(gè) POSIX 線程:

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

在這里,pthread_create 創(chuàng)建一個(gè)新的線程,并讓它可執(zhí)行。下面是關(guān)于參數(shù)的說明:

參數(shù) | 描述
-- |
thread | 指向線程標(biāo)識(shí)符指針。
attr | 一個(gè)不透明的屬性對(duì)象,可以被用來設(shè)置線程屬性。您可以指定線程屬性對(duì)象,也可以使用默認(rèn)值 NULL。
start_routine | 線程運(yùn)行函數(shù)起始地址,一旦線程被創(chuàng)建就會(huì)執(zhí)行。
arg | 運(yùn)行函數(shù)的參數(shù)。它必須通過把引用作為指針強(qiáng)制轉(zhuǎn)換為 void 類型進(jìn)行傳遞。如果沒有傳遞參數(shù),則使用 NULL。

創(chuàng)建線程成功時(shí),函數(shù)返回 0,若返回值不為 0 則說明創(chuàng)建線程失敗。

終止線程

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

#include <pthread.h>
pthread_exit (status) 

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

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

實(shí)例

以下簡(jiǎn)單的實(shí)例代碼使用 pthread_create() 函數(shù)創(chuàng)建了 5 個(gè)線程,每個(gè)線程輸出"Hello Runoob!":

#include <iostream>
// 必須的頭文件是
#include <pthread.h>
 
using namespace std;
 
#define NUM_THREADS 5
 
// 線程的運(yùn)行函數(shù)
void* say_hello(void* args)
{
    cout << "Hello Runoob!" << endl;
}
 
int main()
{
    // 定義線程的 id 變量,多個(gè)變量使用數(shù)組
    pthread_t tids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; ++i)
    {
        //參數(shù)依次是:創(chuàng)建的線程id,線程參數(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è)線程退出后,進(jìn)程才結(jié)束,否則進(jìn)程強(qiáng)制結(jié)束了,線程可能還沒反應(yīng)過來;
    pthread_exit(NULL);
}

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

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

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

$ ./test.o
Hello Runoob!
Hello Runoob!
Hello Runoob!
Hello Runoob!
Hello Runoob!

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

//文件名: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)制類型轉(zhuǎn)換,由無類型指針變?yōu)檎螖?shù)指針,然后再讀取
   int tid = *((int*)threadid);
   cout << "Hello Runoob! 線程 ID, " << tid << endl;
   pthread_exit(NULL);
}
 
int main ()
{
   pthread_t threads[NUM_THREADS];
   int indexes[NUM_THREADS];// 用數(shù)組來保存i的值
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){      
      cout << "main() : 創(chuàng)建線程, " << i << endl;
      indexes[i] = i; //先保存i的值
      // 傳入的時(shí)候必須強(qiáng)制轉(zhuǎn)換為void* 類型,即無類型指針        
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)&(indexes[i]));
      if (rc){
         cout << "Error:無法創(chuàng)建線程," << 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)建線程, 0
main() : 創(chuàng)建線程, 1
main() : 創(chuàng)建線程, 2
main() : 創(chuàng)建線程, 3
main() : 創(chuàng)建線程, 4
Hello Runoob! 線程 ID, 4
Hello Runoob! 線程 ID, 3
Hello Runoob! 線程 ID, 2
Hello Runoob! 線程 ID, 1
Hello Runoob! 線程 ID, 0

向線程傳遞參數(shù)

這個(gè)實(shí)例演示了如何通過結(jié)構(gòu)傳遞多個(gè)參數(shù)。您可以在線程回調(diào)中傳遞任意的數(shù)據(jù)類型,因?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

連接和分離線程

我們可以使用以下兩個(gè)函數(shù)來連接或分離線程:

pthread_join (threadid, status) 
pthread_detach (threadid) 
  • pthread_join() 子程序阻礙調(diào)用程序,直到指定的 threadid 線程終止為止。
  • 當(dāng)創(chuàng)建一個(gè)線程時(shí),它的某個(gè)屬性會(huì)定義它是否是可連接的(joinable)或可分離的(detached)。

只有創(chuàng)建時(shí)定義為可連接的線程才可以被連接。如果線程創(chuàng)建時(shí)被定義為可分離的,則它永遠(yuǎn)也不能被連接。

這個(gè)實(shí)例演示了如何使用 pthread_join() 函數(shù)來等待線程的完成。

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

當(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.

代碼鏈接:https://github.com/karst87/cpp/tree/master/learning/com.runoob

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容