Boost call_once例子

void call_once(void (*func)(), once_flag& flag);
当有线程执行该函数的时候,其他的线程运行到该函数,会一直等待,直到该函数被完全执行,执行完成之后flag的值会被修改,一般只是修改一次,接下来的Thrift将会使用到。

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

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

void Init()
{
        ++i;
}

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

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

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

g++  test.cpp  -lboost_thread

结果显示,全局变量i仅被执行了一次++操作,而变量j则在两个线程中均执行了++操作


猜你喜欢

转载自blog.51cto.com/fengyuzaitu/2459230