9

Is there a way in c++ to get the id of the "main" program thread?

I see that std::this_thread::get_id() gets the id of the currently executing thread but I need the id of the main, original program thread. I don't see any function to get this.

The reason is that I have some non thread safe internal functions that must only be called on the original thread of the application so to be safe I want to do :-

assert(std::this_thread::get_id() == std::main_thread::get_id());

But there of course isn't a function to do that, and I can't see any way to get that information.

Niall
  • 30,036
  • 10
  • 99
  • 142
jcoder
  • 29,554
  • 19
  • 87
  • 130
  • 2
    Ok I feel stupid, all the comments have just been along the lines of "just save it" in the main thread when it starts up. Yeah, I was looking for something more complicated and missed the obvious and trivial answer. Thanks everyone. – jcoder Nov 08 '12 at 11:21
  • Wondering if I should just delete this question as the answer is so trivial it's embarasing to have asked it. Is that the done thing? Or should I just leave it for future reference? – jcoder Nov 08 '12 at 11:30
  • The question is ok, and maybe you don't have access to the `main()`. Another observation is that `std::main_thread` (C++11) can be replaced wtih `boost::main_thread`. – Liviu Sep 22 '14 at 14:26

2 Answers2

18

You could save it while this_thread is still the original thread:

std::thread::id main_thread_id;

int main() {
    main_thread_id = std::this_thread::get_id(); // gotcha!
    /* go on */
}
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
3

This topic seems to be discussed quite a few times here, like in this topic:

You can find some solutions, but I'd just think the other way round... When starting the new threads, just supply the id of the main thread to them, and store that in a field in the other threads. If that is not going to change throughout the threads' life, you're good to go, you can reference the "main" thread by those handles.

Community
  • 1
  • 1
ppeterka
  • 20,583
  • 6
  • 63
  • 78