thread

说明

  • 静态函数this_thread::get_id()可以获得当前线程的线程ID。
  • 静态函数thread::this_thread::sleep()可以让当前线程睡眠一段时间或到指定时间,
  • 静态函数thread::hardware_concurrency()可以获得当前CPU的内核数量。
  • 静态函数this_thread::yield()指示当前线程放弃时间片,允许其他线程运行。

简易使用

#include "boost\thread.hpp"

void PrintThreadFunc(const int& n, const string& str)
{
    cout << str << n << endl;
}

int main()
{    
    int n1 = 1;
    string str1 = "hello";
    boost::thread t1(PrintThreadFunc, ref(n1), ref(str1));

    int n2 = 2;
    string str2 = "boost";
    function<void()> fun = bind(PrintThreadFunc, ref(n2), ref(str2));
    boost::thread t2(fun);

    t1.timed_join(boost::posix_time::seconds(1)); //最多等待1秒
    t2.join(); //一直等待

    return 0;
}

中断线程

线程内部

void ThreadFun()
try
{
    //函数体
}
catch (boost::thread_interrupted&)
{
    //异常处理
}

线程外部

t.interrupt();

线程组

说明

  • 线程组thread_group用于管理一组创建的线程,成员函数create_thread()可以创建thread对象并运行线程,
  • 也可以创建thread对象后使用成员函数add_thread()来加入线程组。成员函数create_thread()的声明如下:
template<typename F>
thread* create_thread(F threadfunc);

使用

    boost::thread_group tg;
    
    int n1 = 0;
    tg.create_thread(bind(ThreadFun1, n1, "c++"));
    int n2 = 0;
    tg.create_thread(bind(ThreadFun2, n2, "python"));

    tg.join_all();

call_once()

说明

  • call_once()用来设置在多线程环境下指定的函数只被调用一次。

使用

int g_count ;
void init_count(int x)
{
	cout << "should call once "<<endl;
    g_count = x;
}

void call_func ()
{
    static once_flag once ;
    call_once(once,init_count,10);
    
}

int main()
{
    boost::thread t (call_func);
    boost::thread t (call_func);
}