【发布时间】: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