Application without std::condition_variable:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>
std::mutex mutex;
std::queue<int> queue;
int counter;
void loadData()
{
while(true)
{
std::unique_lock<std::mutex> lock(mutex);
queue.push(++counter);
lock.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void writeData()
{
while(true)
{
std::lock_guard<std::mutex> lock(mutex);
while(queue.size() > 0)
{
std::cout << queue.front() << std::endl;
queue.pop();
}
}
}
int main()
{
std::thread thread1(loadData);
std::thread thread2(writeData);
thread1.join();
thread2.join();
return 0;
}
Application with std::condition_variable:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>
std::mutex mutex;
std::queue<int> queue;
std::condition_variable condition_variable;
int counter;
void loadData()
{
while(true)
{
std::unique_lock<std::mutex> lock(mutex);
queue.push(++counter);
lock.unlock();
condition_variable.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void writeData()
{
while(true)
{
std::unique_lock<std::mutex> lock(mutex);
condition_variable.wait(lock, [](){return !queue.empty();});
std::cout << queue.front() << std::endl;
queue.pop();
}
}
int main()
{
std::thread thread1(loadData);
std::thread thread2(writeData);
thread1.join();
thread2.join();
return 0;
}
If I am right, it means that second version of this application is unsafe, because of queue.empty() function, which is used without any synchronization, so there are no locks. And there is my question: Should we use condition_variables if they cause problems like this one mentioned before?