Compilation error : 'this' cannot be implicitly captured in this context
Asked Answered
D

1

38

I am trying to add a condition_variable to handle threads, but get a compilation error at this line:

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

Looks like the for the variable this->ready, the this is not in the right scope.

In Java this can be handled with TestThread.this, is there anything in C++ doing the same?

void TestThread::Thread_Activity()
    {
        std::cout << "Thread started \n";
        // Wait until ThreadA() sends data
        {
            std::unique_lock<std::mutex> lk(m);
            this->cv.wait(lk, []{return ready;});
        }
    
        std::cout << "Thread is processing data\n";
        data += " after processing";
        // Send data back to ThreadA through the condition variable
        {
           // std::lock_guard<std::mutex> lk(m);
            processed = true;
           // std::cout << "Thread B signals data processing completed\n";
        }
    
    }
Disjunctive answered 26/7, 2016 at 16:57 Comment(1)
Side note: in a different context it may be unnecessary to capture this at all. For example, static class methods and variables can be used in a lambda without capturing this.Imperium
W
70

You need to capture the this pointer:

this->cv.wait(lk, [this]{return ready;});
Worked answered 26/7, 2016 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.