【问题标题】:C++11: Ensure that GUI calls are made from the main threadC++11:确保从主线程进行 GUI 调用
【发布时间】:2017-09-26 21:00:47
【问题描述】:

我有一个多线程 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 可能会因某种原因而改变。这会发生吗?

【问题讨论】:

  • 什么 C++ 标准?什么平台?什么编译器?只是为了了解基本信息:)
  • @JesperJuhl C++11!它是跨平台的,Linux 和 Windows。
  • 您的检查方式是有效的,(假设您在主线程中创建GuiElement)。
  • @Jarod42 感谢您的回答。 :)
  • @JesperJuhl:这些信息都不是必需的。 OP 使用std::thread,所以它必须是 C++11、C++14 或 C++17。所有这些标准的答案都是相同的。而且我不知道有任何编译器会出错。

标签: c++ multithreading user-interface c++11 thread-safety


【解决方案1】:

对于您关于线程更改 id 的可能性的问题,您可以继续讨论,只要线程正在运行,就可以安全地假设线程 id 不会更改。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 2011-04-25
    • 1970-01-01
    • 2015-05-03
    • 2021-01-05
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多