In .h

class A{ std::thread thread; std::mutex mutex; std::condition_variable cv; bool run; std::queue< ResourceData > queue; public: bool resource_empty( void ){return !this->queue.empty();} ... 

In implementation

 while( this->run ){ std::unique_lock<std::mutex> lk(this->mutex); cv.wait( lk, /* Сюда нужно вставить указатель на функцию */ this->resource_empty ); // просто this->queue.empty не работает // cv.wait( lk, []{ return !this->queue.empty();} ); и так } 

It works only if the function is outside the class and without parameters .

I want the thread to wait for data to arrive in the queue. Maybe then there is another way of using class data without std :: condition_variable?

    1 answer 1

    First, you can always use the wait method without the second parameter.

    Secondly, to use an external variable in the closure - it must first be captured:

     cv.wait( lk, [this] { return !this->queue.empty(); } ); 

    Writing this-> optional - in lambda just as in any other place, you can refer to this members simply by name. But you need to capture this anyway:

     cv.wait( lk, [this] { return !queue.empty(); } ); 

    There is also a universal way - to capture all the necessary variables by value:

     cv.wait( lk, [=] { return !queue.empty(); } ); 

    or by reference:

     cv.wait( lk, [&] { return !queue.empty(); } ); 

    Use these methods with caution: uncontrolled seizure of variables can lead to memory leaks or memory corruption. But in relation to cv.wait using [=] or [&] does not threaten anything.