《C++并发编程实战》第二版中有如下代码,我在VS2015和其他版本中都没有运行起来。
#include <thread>
#include <utility>
#include <stdexcept>
class scoped_thread
{
std::thread t;
public:
explicit scoped_thread(std::thread t_):
t(std::move(t_))
{
if(!t.joinable())
throw std::logic_error("No thread");
}
~scoped_thread()
{
t.join();
}
scoped_thread(scoped_thread const&)=delete;
scoped_thread& operator=(scoped_thread const&)=delete;
};
void do_something(int& i)
{
++i;
}
struct func
{
int& i;
func(int& i_):i(i_){}
void operator()()
{
for(unsigned j=0;j<1000000;++j)
{
do_something(i);
}
}
};
void do_something_in_current_thread()
{}
void f()
{
int some_local_state;
scoped_thread t(std::thread(func(some_local_state)));
do_something_in_current_thread();
}
int main()
{
f();
}
为什么do_something函数没有运行?乃至scoped_thread的构造函数都没有执行?
void thread_func(int& var)
{
std::cout << var << std::endl;
}
void f()
{
int some_local_state = 10;
//std::thread t1(func(some_local_state));
//std::thread a(thread_func,std::ref(some_local_state));
//functionTest(std::move(a));
scoped_thread t(std::thread(thread_func, std::ref(some_local_state)));
//scoped_thread t(std::thread(func(some_local_state)));
do_something_in_current_thread();
}
这样就能运行了,应该是仿函数的问题,但是具体是什么原因不清楚。