Here is my piece of code, where I am trying to access a resource in two different threads in a detach mode, but I am not able read the update value of m_dataLoaded in second thread. It continues to wait even if the condition is met. I don't understand the logic behind this and how can I achieve this??
Header file application.h
#ifndef APPLICATION_H
#define APPLICATION_H
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
class Application
{
public:
Application();
bool isDataLoaded();
void loadData();
void mainTask();
private:
bool m_dataLoaded;
std::condition_variable m_condVar;
std::mutex m_mutex;
};
#endif // APPLICATION_H
Source file application.cpp
#include "application.h"
Application::Application()
: m_dataLoaded(false)
{
}
bool Application::isDataLoaded()
{
return m_dataLoaded;
}
void Application::loadData()
{
std::cout << "Inside loadData" << std::endl;
std::lock_guard<std::mutex> gaurd(m_mutex);
while(true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
m_dataLoaded = true;
if(m_dataLoaded)
{
m_condVar.notify_one();
}
}
}
void Application::mainTask()
{
std::cout << "Inside mainTask" << std::endl;
std::unique_lock<std::mutex> u_lock(m_mutex);
while(true)
{
std::cout << "Waiting..." << std::endl;
m_condVar.wait(u_lock, std::bind(&Application::isDataLoaded, this));
std::cout << "Start Data Processing: " << std::endl;
m_dataLoaded = false;
}
std::cout << "Break out of the loop" << std::endl;
}
main file main.cpp
#include "application.h"
int main()
{
Application *app = new Application;
std::thread *thread_1 = new std::thread(&Application::mainTask, app);
std::thread *thread_2 = new std::thread(&Application::loadData, app);
thread_2->detach();
thread_1->detach();
while(1)
{
}
return 0;
}
For above piece of code thread_1 keeps on waiting... I don't understand why this happens. Any help would be appreciated...