Boost call_once例子

void call_once(void (*func)(), once_flag& flag);
當有線程執行該函數的時候,其餘的線程運行到該函數,會一直等待,直到該函數被徹底執行,執行完成以後flag的值會被修改,通常只是修改一次,接下來的Thrift將會使用到。ios

#include <boost/thread/thread.hpp>
#include <boost/thread/once.hpp>
#include <iostream>ide

int i = 0;
int j = 0;
boost::once_flag flag = BOOST_ONCE_INIT;函數

void Init()
{
        ++i;
}線程

void ThreadFunc()
{
        boost::call_once(&Init, flag);
        ++j;
}it

int main()
{
        boost::thread thrd1(&ThreadFunc);
        boost::thread thrd2(&ThreadFunc);
        thrd1.join();
        thrd2.join();io

        std::cout<<i<<std::endl;
        std::cout<<j<<std::endl;
        return 0;
}class

g++  test.cpp  -lboost_threadthread

結果顯示,全局變量i僅被執行了一次++操做,而變量j則在兩個線程中均執行了++操做test

相關文章
相關標籤/搜索