boost::thread庫 並發編程__boost

來源:互聯網
上載者:User

所在檔案和命名空間:

#include <boost/thread.hpp>using namespace boost;
1. 時間功能

多線程編程經常要用到逾時處理,需要表示時間的概念,thread庫直接利用date_tiem庫提供對時間的支援。

this_thread::sleep(posix_time::seconds(2));  //當前線程睡眠兩秒//this_thread是thread的子命名空間
2. boost::mutex 互斥量

互斥量:一種線程同步手段,可以在多線程編程中防止多個線程同時操作共用資源(或稱臨界區)。

//最簡單最常用的互斥量類型:獨佔式互斥量typedef boost::mutex mutex_t;//基本用法mutex_t mu;mu.lock();//do somethingmu.unlock();
3. RAII型的lock_guard類

直接使用mutex的lock()函數來鎖定互斥量不夠方便,且在發生異常退出範圍等情況下很可能忘記解鎖。
故,thread庫提供了RAII型lock_guard類,輔助:在構造時鎖定互斥量,析構時自動解鎖。
mutex類使用內部類型定義了兩種lock_guard對象:
1. scoped_lock
2. scoped_try_lock

mutex mu;mutex::scoped_lock lock(mu);//do something
4. 互斥量執行個體

使用mutex實現一個原子操作的計數器basic_atom,多安全執行緒的計數:

template<typename T>class basic_atom:boost::noncopyable{public:    //建構函式    basic_atom(T x=T()):n(x){}    //前置式遞增操作    T operator++(){        mutex::scoped_lock lock(mu);        return ++n;    }    T operator()(){        return n;    }private:    T n;    typedef mutex mutex_t;    mutex_t mu;};typedef basic_atom<int> atom_int;
5. 線程

thread類是thread庫的核心類,從類摘要中就可以看出thread的操作方式:

當建立一個thread對象後,線程就立刻開始執行。 join()和timed_join()方法等待線程結束。
join()一直阻塞等待,直到線程結束。 timed_join()阻塞等待線程結束,或阻塞等待一定的時間段,然後不管線程是否結束都返回。 detach()與線程執行體分離,線程執行體不受影響的繼續執行直到運行結束。 可以使用bind()和function庫。 thread類的3個靜態成員函數:
yield() 指示當前線程放棄時間片,允許其他的線程運行。 sleep() 讓線程睡眠等待一小段時間。 hardware_concurrency() 獲得硬體系統可並行的線程數量,即CPU數量。 thread::this_thread 子命名空間:
get_id() 獲得線程ID yield() 放棄時間片 sleep() 睡眠等待 at_thread_exit(func)函數,允許“登記”一個線程在結束的時候執行可調用物func,無論線程是否被中斷。 interrupt() 中斷線程,允許正在執行的線程被中斷,被中斷的線程會拋出一個thread_interrupted異常。

使用執行個體:

//#define BOOST_DATE_TIME_SOURCE//#define BOOST_THREAD_NO_LIB#include <boost/thread.hpp>#include <boost/ref.hpp>#include < boost/typeof/typeof.hpp >#include <boost/bind.hpp>#include <boost/function.hpp>using namespace boost;#include <iostream>#include <string>using std::cout;using std::endl;using std::string;//typedef mutex mutex_t;//mutex_t io_mu;template<typename T>class basic_atom:boost::noncopyable{public:    //建構函式    basic_atom(T x=T()):n(x){}    //前置式遞增操作    T operator++(){        mutex::scoped_lock lock(mu);        return ++n;    }    T operator()(){        return n;    }private:    T n;    typedef mutex mutex_t;    mutex_t mu;};typedef basic_atom<int> atom_int;mutex io_mu;void end_msg(){    cout<<"this is the end of the thread"<<endl;}void printing(atom_int &x,const string &str){    for(int i=0;i<5;i++){        mutex::scoped_lock lock(io_mu);        cout<<str<<++x<<endl;    }    this_thread::at_thread_exit(bind(end_msg));}void fun(){    //cout<<this_thread::get_id()<<endl;    cout<<"liudong"<<endl;    cout<<this_thread::get_id()<<endl;}void interrupt_func(atom_int &x,const string &str){    try{        for(int i=0;i<5;i++){            this_thread::sleep(posix_time::seconds(1));            mutex::scoped_lock lock(io_mu);            cout<<str<<++x<<endl;            this_thread::interruption_point();  //指定線程中斷點。        }    }    catch(thread_interrupted&){        cout<<"thread: "<<this_thread::get_id()<<"interrupted"<<endl;    }}int main(){    /*    cout<<"cpus is "<<thread::hardware_concurrency()<<endl;    fun();    thread t1(fun);    thread t2(fun);    cout<<this_thread::get_id()<<endl;    //this_thread::sleep(posix_time::seconds(2));    t1.join();    t2.join();    cout<<"all joined"<<endl;    */    atom_int x;    //thread t1=thread(printing,ref(x),"hello");    thread t1(printing,ref(x),"thread1 ");    function<void()> f=boost::bind(printing,ref(x),"thread2 ");    //thread t2=thread(printing,ref(x),"boost");    //f=boost::bind(interrupt_func,ref(x),"thread2");    thread t2=thread(f);    //t1.join();    /*    t1.detach();    t2.interrupt();    t2.join();    */    /*    thread_group tg;    tg.add_thread(&t1);    tg.add_thread(&t2);    tg.join_all();    tg.~thread_group();    */    t1.join();    t2.join();    cout<<"the end of main program"<<endl;    return 0;}
6. 線程組(線程池)thread_group類

thread類提供thread_group類用於管理一組線程,就像是一個線程池,它內部使用std::list<thread*>來容納建立的thread對象。
類摘要如下:

使用thread_group,可以為程式建立一個類似於全域線程池對象,統一管理程式中使用的thread。 7. 條件變數

條件變數是thread庫提供的另一種用於等待的同步機制,可以實現線程間的通訊,它必須和互斥量配合使用,等待另一個線程中某個事件的發送(滿足某個條件),然後線程才能繼續執行。
thread庫提供兩種條件變數對象:
1. condition_variable
2. condition_variable_any (常用,能夠適應更廣泛的互斥量類型)

使用條件變數實現的 生產者-消費者模式的後進先出型(std::stack)緩衝區
見我的另一篇部落格:
http://blog.csdn.net/yvhqbat/article/details/51922153 8. 執行緒區域儲存

執行緒區域儲存(thread local storage)或者稱 線程專有儲存(thread specific storage, 簡稱 tss):使變數用起來就像每個線程獨立擁有,可以簡化多線程應用,提高效能。
thread庫 thread_specific_ptr 實現執行緒區域儲存。 9. at_thread_exit()

線程結束時執行操作。
at_thread_exit(func)函數,允許“登記”一個線程在結束的時候執行可調用物func,無論線程是否被中斷。

at_thread_exit(bind(end_msg,"end"));  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.