Moving a theme in C ++ 11

I am running into some problem while testing examples in 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;
  }
}

      

Only the "Main Thread" is printed out. I found that the constructor didn't fire. Does this mean some kind of problem with the use of thread transfer semantics? My working environment is Ubuntu 16.04 and the compile command is "g ++ -std = C ++ 11 -Wall -pthread file.cpp"

+3


source to share


1 answer


Scoped_thread t2(std::thread(myfunc));

      

Here we have a somewhat unconventional case of the most unpleasant parsing . The point is that the following forward declaration functions are equivalent:

void f(int arg);
void f(int (arg));

      



Hence, it is Scoped_thread t2(std::thread(myfunc));

parsed as a forward declaration of a function t2

that returns Scoped_thread

and takes std::thread myfunc

as an argument.

Two solutions:

Scoped_thread t2{std::thread(myfunc)};

      

+1


source







All Articles