samedi 4 décembre 2021

How to use threds to acquire the lock with the new state and release after some fractions of seconds and go back to the previous state using C++

In my application, when i receive an alert message event that time I wanted to display "Red" color blink in the UI and after some fraction of seconds (for eg 5 seconds) it should go back to the previous state (for eg Green)

To achieve this i am planning to use a thread in the constructor, and Once I received the alert notificatin I am doing the notify lock and starting the thread. From the thread, calling the function DisplayColorOnUI(), to set the color and locking it for 5 seconds.

I am new to the threading concept and trying it like as shown below. It is not the working code, but trying it like this. Can someone help me with their thoughts and inputs to proceed this logic.

ForeCastController.h


std::thread m_Notificationthread;
std::mutex m_mutexAlertNotification;
std::condition_variable m_CondVarNotifyPending;
std::mutex m_mutexDisplayColor;

bool m_bIsAlertReceived = false;
bool m_bIsThreadExiting = false;

ForeCastController.cpp


CForeCastController::CForeCastController()
{
    m_Notificationthread = thread(&CForeCastController::IMNotificationThread, this);
}

void CForeCastController::IMNotificationThread()
{
    while (true)
    {
        {
            std::unique_lock<std::mutex> notifyLock(m_mutexAlertNotification);
            m_CondVarNotifyPending.wait(notifyLock, [this]
                {
                    return m_bIsThreadExiting || m_bIsAlertReceived;
                });
            m_bIsAlertReceived = false;

            if (m_bIsThreadExiting)
            {
                notifyLock.unlock();
                break;
            }
            notifyLock.unlock();
        }

        std::this_thread::sleep_for(std::chrono::seconds(5));
        {
            const std::lock_guard<std::mutex> displayColorOnUIlock(m_mutexDisplayColor);
            DisplayColorOnUI();
        }
    }
}

void CForeCastController::SetAlertNotificationStatus()
{
    m_bIsAlertNotification = true;

    std::unique_lock<std::mutex> notifyLock(m_mutexAlertNotification);
    m_bIsAlertReceived = true;
    notifyLock.unlock();
    m_CondVarNotifyPending.notify_one();
}

void CForeCastController::Reset()
{
    {
        std::unique_lock<std::mutex> notifyLock(m_mutexAlertNotification);
        m_bIsThreadExiting = true;
        notifyLock.unlock();
        m_CondVarNotifyPending.notify_one();
    }

    m_Notificationthread.join();
}


int main()
{
    std::shared_ptr<CForeCastController> m_pForecastController = std::make_shared<CForeCastController>();
    m_pForecastController->SetAlertNotificationStatus();
    m_pForecastController->Reset();

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire