Reputation: 26286
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?
Upvotes: 1
Views: 91
Reputation: 80
for your question about the possibility of thread changing the id, you can relay on the that as long as the thread is running, it will be safe to assume that the thread id will not change.
take a look here std::thread::id, it states that the class purpose is to be used key in associative containers.
Upvotes: 1