首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++11中的线程移动

C++11中的线程移动
EN

Stack Overflow用户
提问于 2017-06-11 15:02:39
回答 1查看 136关注 0票数 3

在使用C++并发测试示例时,我遇到了一些问题。

代码语言:javascript
复制
/***
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‘

EN

回答 1

Stack Overflow用户

发布于 2017-06-11 18:31:40

代码语言:javascript
复制
Scoped_thread t2(std::thread(myfunc));

这里我们有一个稍微非常规的most vexing parse案例。问题是:下面的函数转发声明是等价的:

代码语言:javascript
复制
void f(int arg);
void f(int (arg));

因此,Scoped_thread t2(std::thread(myfunc));被解析为函数t2的正向声明,该函数返回Scoped_thread并将std::thread myfunc作为参数。

两种解决方案是:

代码语言:javascript
复制
Scoped_thread t2{std::thread(myfunc)};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44481227

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档