#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
// Wait until main() sends data
std::unique_lock<std::mutex> lk(m, std::defer_lock);
cv.wait(lk, []{return ready;});
// after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";
// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
std::this_thread::sleep_for(std::chrono::seconds(1));
data = "Example data";
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
// wait for the worker
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return processed;});
}
std::cout << "Back in main(), data = " << data << '\n';
worker.join();
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgojaW5jbHVkZSA8dGhyZWFkPgojaW5jbHVkZSA8bXV0ZXg+CiNpbmNsdWRlIDxjb25kaXRpb25fdmFyaWFibGU+CiAKc3RkOjptdXRleCBtOwpzdGQ6OmNvbmRpdGlvbl92YXJpYWJsZSBjdjsKc3RkOjpzdHJpbmcgZGF0YTsKYm9vbCByZWFkeSA9IGZhbHNlOwpib29sIHByb2Nlc3NlZCA9IGZhbHNlOwogCnZvaWQgd29ya2VyX3RocmVhZCgpCnsKICAgIC8vIFdhaXQgdW50aWwgbWFpbigpIHNlbmRzIGRhdGEKICAgIHN0ZDo6dW5pcXVlX2xvY2s8c3RkOjptdXRleD4gbGsobSwgc3RkOjpkZWZlcl9sb2NrKTsKICAgIGN2LndhaXQobGssIFtde3JldHVybiByZWFkeTt9KTsKIAogICAgLy8gYWZ0ZXIgdGhlIHdhaXQsIHdlIG93biB0aGUgbG9jay4KICAgIHN0ZDo6Y291dCA8PCAiV29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