lundi 7 août 2023

Get Status if std::call_once has been executed?

I'm developing a C++ library that will allow me to set value to POD only once (something analogous to flutter's final keyword.
In my application their are several configuration that are only set once (during initialization) and remain valid of the life-time of the program.
I'm using std::once and std::call_once for the same.
I've hit a snag whereby I'm unable to check if the std::call_once has been executed.
I was think of adding std::atomic_bool to track the status of std::call_once.
I was wondering if their is a better alternative than boolean flag where by I can use something associated std::once_flag object to get the status of std::call_once execution.

Code:

#pragma once
#include <mutex>

class DataNotSetException: public std::exception
{
public:
    const char* message = "Data Not Set before Get Operation";
    char* what()
    {
        return const_cast<char *>(this->message);
    }
};

template<typename T>
class SetOnce
{
private:
    T data;
    std::once_flag flag;
    void do_once(const T& data);
public:
    T get(void) const;
    void set(const T& data);
    bool is_set(void) const;

};

template<typename T>
inline void SetOnce<T>::do_once(const T& data)
{
    this->data = data;
}

//If data is not been set throw data not set exception (DataNotSetException)
template<typename T>
inline T SetOnce<T>::get(void) const
{
    if (this->is_set() == true)
    {
        return this->data;
    }
    else
    {
        throw DataNotSetException();
    }
}

template<typename T>
inline void SetOnce<T>::set(const T& data)
{
    std::call_once(this->flag, this->do_once, data);
}

template<typename T>
inline bool SetOnce<T>::is_set(void) const
{
    //How to check if the call_once has been executed
}

Edit

I'm working on a real-time system and hence wish to avoid delay associated blocking (busy-wait) mutex calls on get operation.
The get operation is expected to have low response time and high frequency of execution.

Aucun commentaire:

Enregistrer un commentaire