Croll
Croll

Reputation: 3791

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!

Upvotes: 4

Views: 2436

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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.

Upvotes: 5

Radon
Radon

Reputation: 93

You should use if(m_thread.joinable()) m_thread.join();. Never heard that it is unsafe.

Upvotes: -4

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

Upvotes: 1

Related Questions