How to wait and notify like in Java In C/C++ for shared memory between two or more thread?I use pthread library.
In your title, you blend C and C++ together so casually into "C/C++". I hope, you are not writing a program that is a mixture of the two.
If you are using C++11, you will find a portable and (because C++, so) much safer/easier-to-use alternative to pthreads (on POSIX systems, it usually uses pthreads under the hood though).
You can use std::condition_variable + std::mutex for wait/notify. This example shows how:
#include
#include
#include
#include
#include
std::mutex m;
std::condition_variable cv;
std::string data;
bool mainReady = false;
bool workerReader = false;
void worker_thread()
{
// Wait until main() sends data
{
std::unique_lock lk(m);
cv.wait(lk, []{return mainReady;});
}
std::cout << "Worker thread is processing data: " << data << std::endl;
data += " after processing";
// Send data back to main()
{
std::lock_guard lk(m);
workerReady = true;
std::cout << "Worker thread signals data processing completed\n";
}
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
// send data to the worker thread
{
std::lock_guard lk(m);
mainReady = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
// wait for the worker
{
std::unique_lock lk(m);
cv.wait(lk, []{return workerReady;});
}
std::cout << "Back in main(), data = " << data << '\n';
// wait until worker dies finishes execution
worker.join();
}
This code also highlights some other strengths that C++ has over C: