定义std::thread对象:
1. 函数方式
#include <thread>
void do_some_work();
std::thread my_thread(do_some_work);
2. 对象方式
#include <iostream>
#include <thread>
class background_task
{
public:
//重载()需要两个(),类比重载++, Test Test::operator++(int)
void operator()()const
{
std::cout << "Hello\n";
}
};
//background_task f;
//std::thread my_thread(f);
int main()
{
background_task f;
std::thread my_thread(f);
my_thread.join();
return 0;
}
定义std::thread对象的时候需要注意:
如果给std::thread对象的构造函数传入一个临时对象而不是一个正式定义的对象作为参数的时候,会被编译器解释成声明一个函数。如下:
std::thread my_thread(background_task());
会被当做声明一个函数my_thread,返回值为std::thread, 函数参数为函数指针background_task func (void),而不是定义一个函数对象。
declares a function my_thread that takes a single parameter (of type pointer to a function taking no parameters and returning a background_task object) and returns a std::thread object, rather than launching a new thread.
如何避免这种情况?
方法1: 将参数再用一个()括起来。
std::thread my_thread((background_task()));
the extra parentheses prevent interpretation as a function declaration, thus allowing my_thread to be declared as a variable of type std::