在使用C++并发测试示例时,我遇到了一些问题。
/***
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;
}
}打印输出时,仅显示“主线程”。我发现构造函数没有启动。这是否表明使用线程移动语义存在问题?我的工作环境是Ubuntu16.04,编译命令是'g++ -std=c++11 -Wall -pthread file.cpp‘
发布于 2017-06-11 18:31:40
Scoped_thread t2(std::thread(myfunc));这里我们有一个稍微非常规的most vexing parse案例。问题是:下面的函数转发声明是等价的:
void f(int arg);
void f(int (arg));因此,Scoped_thread t2(std::thread(myfunc));被解析为函数t2的正向声明,该函数返回Scoped_thread并将std::thread myfunc作为参数。
两种解决方案是:
Scoped_thread t2{std::thread(myfunc)};https://stackoverflow.com/questions/44481227
复制相似问题