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!

+3


source to share


3 answers


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.

+3


source


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.).



+1


source


You must use if(m_thread.joinable()) m_thread.join();

. I have never heard that it is not safe.

-4


source







All Articles