Multithreading with functors
Sep 22, 2014 at 9:23am UTC
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
Sep 22, 2014 at 10:08am UTC
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) ) ;
Sep 22, 2014 at 11:47am UTC
Thank you very much JLBorges.
That is exactly what I needed.
Bidski
Topic archived. No new replies allowed.