C/C++ 多線程(程序猿面試重點)CodeBlocks-CB的pthreads使用


C++ 多線程

本文主要講一下C++多線程

線程好處

·使用線程可以把占據長時間的程序中的任務放到后台去處理

·程序的運行速度可能加快

 可以釋放一些珍貴的資源如內存占用等等。

但是多線程是為了同步完成多項任務,不是為了提高運行效率,而是為了提高資源使用效率來提高系統的效率。線程是在同一時間需要完成多項任務的時候實現的。

 

首先  我們現在在學校使用的和大賽使用的C++編程軟件一般都是codeblocks(湖南省比賽是的,其他就不知道了)

但是在CodeBlocks中間  我們是不能直接使用線程的  需要設置一下

創建線程

  線程的頭文件與現場創建格式

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

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

參數說明

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

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

線程有創建  自然也就有結束

下面介紹一下結束線程的方法:

終止線程

使用下面的方法  我們可以結束線程

#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);
}
View Code

 


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


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 ); //注銷鎖
}
View Code

 


測試結果:

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
View Code

 


可知,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 ); //正常退出
}
View Code

 


測試結果:
先在線程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

 

 


免責聲明!

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



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