C++98 标准中并没有线程库的存在,直到 C++11 中才终于提供了多线程的标准库,提供了管理线程、保护共享数据、线程间同步操作、原子操作等类。多线程库对应的头文件是 #include <thread> ,类名为 std::thread 。
int testFun(int numb)
{
cout << "function is runing" << endl;
cout << "this thread ID:"<<std::this_thread::get_id() << endl;
std::chrono::seconds dura(5);
std::this_thread::sleep_for(dura);
return ++numb;
}
调用方式:
//* std::sthread
std::thread func1(&testFun,5);
m_obj.join();
而线程毕竟是比较贴近系统的东西,使用起来仍然不是很方便,特别是线程同步及获取线程运行结果上就更加麻烦。我们不能简单的通过 thread.join() 得到结果,必须定义一个线程共享的变量来传递结果,同时还要考虑线程间的互斥问题。好在 C++11 中提供了一个相对简单的异步接口 std::async ,通过这个接口可以简单的创建线程并通过 std::future 中获取结果。
函数原型:
//(C++11 起) (C++17 前)
template< class Function, class... Args>
std::future<std::result_of_t<std::decay_t<Function>(std::decay_t<Args>...)>