Multithreading with functors

I have a semaphore class which I have defined as follows

1
2
3
4
5
6
7
8
9
10
11
12
class Semaphore
{
public:
  Semaphore();
  void wait();
  void signal();

private:
  std::mutex countMutex;
  std::condition_variable condition;
  int count;
};


I then have another class which has a semaphore as a private data member. This class has also overloaded operator().
1
2
3
4
5
6
7
8
9
10
class Worker
{
public:
  Worker();

  void operator() ();

private: 
  Semaphore ticket;
};


In my main function I am trying to do the following
Worker w;
std::thread t(w);

However, this fails to compile since std::mutex and std::condition_variable are not moveable.

Can anyone suggest a way for me to work around this constraint? I am drawing some serious blanks here.

Thanks In Advance
Bidski
std::mutx and std::condition_variable (and consequently Semaphore and Worker) are not CopyConstructible, MoveConstructible, CopyAssignable or MoveAssignable types.

Pass the Worker object by reference (wraped in std::reference_wrapper<>),
and make sure that the life-time of the Worker object does not end before a join().

For instance:
1
2
static Worker w;
std::thread t( std:ref(w) ) ;
Thank you very much JLBorges.

That is exactly what I needed.

Bidski
Topic archived. No new replies allowed.