C 11:确保通过主线程进行GUI调用

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

本文关键字:线程 GUI 调用 确保      更新时间:2023-10-16

我有一个多线程GUI程序,我需要在另一个线程中排队的事件。我想确保GUI调用主要是由主线程进行的。调用std::this_thread::get_id()是否在整个应用程序中保留其值?

我正在计划这样的事情:

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
    }
};

这是正确的事情吗?还是可以实现此功能的更好的东西?

虽然不太可能,但我担心由于某种原因,线程ID可能会更改。这会发生吗?

对于您有关线程更改ID的可能性的问题,只要线程运行,您就可以在该线程上传递,可以肯定地假设线程ID不会更改。

在这里查看std :: thread :: id,它指出类目的是在关联容器中使用键。