在测试《C++ Concurrency in Action》示例代码时,我遇到了一些问题。
/***
Scoped_thread
Help explain the move semantics of Scoped_guard
@c++ Concurrency in Action
***/
#include <thread>
#include <iostream>
using namespace std;
class Scoped_thread
{
std::thread t;
public:
Scoped_thread(std::thread _t):
t(std::move(_t))
{
cout << "Success?" << endl;
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;
};
struct func
{
int& i;
func(int& i):i(i) {}
void operator()()
{
for (unsigned j = 0; j < 1000000; j++)
{
cout << j << endl;
}
}
};
int main()
{
int some_local_state = 1;
func myfunc(some_local_state);
Scoped_thread t2(std::thread(myfunc));
for (unsigned j = 0; j < 1000; j++)
{
cout << "Main thread " << j << endl;
}
}
打印输出时,只有“主线程”出现。我发现构造函数没有启动。这是否表示使用线程移动语义存在问题?我的工作环境是Ubuntu 16.04,编译命令是'g++ -std=c++11 -Wall -pthread file.cpp'