Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if code is running in specific thread

In my application i run background operation using this snippet:

m_thread = std::thread(&MyClass::BackOp, this);

Sometimes different threads (including m_thread itself, possibly) in my application call function Close() which waits for background thread to complete its operation:

if(m_thread.joinable()) m_thread.join();

And this is unsafe behaviour, if i am right, it may cause deadlock.

Can i determine in my Close() function text, if it is running in my background thread, to skip "joining"?

Thank you!

like image 638
Croll Avatar asked Sep 05 '25 03:09

Croll


2 Answers

Can i determine in my Close() function if it is running in my background thread, to skip "joining"?

Yes, you can use the std::this_thread::get_id() function and compare with m_thread.get_id() to determine if the routine runs within the same std::thread instance.

like image 97
πάντα ῥεῖ Avatar answered Sep 07 '25 22:09

πάντα ῥεῖ


I believe you want to use std::this_thread::get_id and compare its result to the result of std::thread::get_id (of your "background" thread). Or have some thread local variables (perhaps storing these at start of thread, etc.).

like image 23
Basile Starynkevitch Avatar answered Sep 07 '25 23:09

Basile Starynkevitch