views:

880

answers:

3

How do I set a name to a Win32 thread. I did'nt find any Win32 API to achieve the same. Basically I want to add the Thread Name in the Log file. Is TLS (Thread Local Storage) the only way to do it?

+5  A: 

Does this help ? How to: Set a Thread Name in Native Code

In managed code, it is as easy as setting the Name property of the corresponding Thread object.

Gishu
I guess its only for the Visual Studio debugger to display the thread name.
Canopus
+1  A: 

You can always store this information for yourself in a suitable data structure. Use a hash or a map to map GetThreadId() to this name. Since GetThreadId() is always a unique identifier, this works just fine.

Cheers !

Of course, if he's creating many threads, that hashmap will slowly fill up and use more and more memory, so some cleanup procedure is probably a good thing as well.

You're absolutely right. When a thread dies, it's corresponding entry in the map should naturally be removed.

Magnus Skog
Of course, if he's creating many threads, that hashmap will slowly fill up and use more and more memory, so some cleanup procedure is probably a good thing as well.
Lasse V. Karlsen
A: 

If you want to see the name of your thread in the debugger (windbg or visual studio): http://blogs.msdn.com/stevejs/archive/2005/12/19/505815.aspx

I'm not actually sure if there's a reverse method to get the thread name. But TLS sounds like the way to go.

selbie