vendredi 28 avril 2017

C++11: Ensure that GUI calls are made from the main thread

I have a multithreaded GUI program where I need to queue events that are called from another thread. I would like to make sure that GUI calls are primarily made from the main thread. Does the call std::this_thread::get_id() preserve its value throughout the whole application?

I'm planning something like this:

GuiElement
{
    std::thread::id main_thread_id;
public:
    GuiElement()
    {
        main_thread_id = std::this_thread::get_id();
    }

    void thread_check() 
    {
        if(std::this_thread::get_id() != this->main_thread_id) 
        {
            throw std::runtime_error("You can't call this from a different thread");
        }
    }

    void remove_element(const std::string& element_name)
    {
        this->thread_check();
        //do stuff
    }
};

Is this the right thing to do? Or is there something better to achieve this functionality?

Although unlikely, but I'm worried that a thread id might change for some reason. Can this happen?

Aucun commentaire:

Enregistrer un commentaire