Determine if your code is running on a specific thread
In my application, I am starting a background activity using this snippet:
m_thread = std::thread(&MyClass::BackOp, this);
Sometimes different threads (including m_thread
themselves, perhaps) in my application call function Close()
that waits for the background thread to complete:
if(m_thread.joinable()) m_thread.join();
And this is unsafe behavior, if I'm right it could lead to deadlock.
Can I define the text in the function Close()
text if it is running on my background thread to skip the "connection"?
Thank!
source to share
Can I tell in my function
Close()
if it is running on my background thread to skip the "connection"?
Yes, you can use a function std::this_thread::get_id()
and compare with m_thread.get_id()
to determine if a routine runs within the same std::thread
instance.
source to share
I believe you want to use std :: this_thread :: get_id and compare its result with that of std :: thread :: get_id (from your "background" thread). Or have some thread local variables (maybe store them when starting the thread, etc.).
source to share