views:

187

answers:

2

On Win32, how can a C++ program determine how many threads are active in my program's process? Is there an API call?

+1  A: 

You can use Tool Help API to enumerate the current processes running and within each process the threads running. Of course by the time you have completed the analysis more tasks and threads may have started and others may have ended.

Stephen Nutt
+1 before edit -- -1 after. Why not use the off the shelf API for this purpose? The process status link you had led right to the correct answer!
Billy ONeal
Pray tell, what was it?
Jive Dadson
@Jive Dadson: http://msdn.microsoft.com/en-us/library/ms683210(VS.85).aspx -- Though I think we both misinterpreted the question. -- For that reason removed downvote :P
Billy ONeal
@Billy The PSAPI only given a list of processes not threads, the toolhelp API is required to enumerate both processes and threads
Stephen Nutt
@Stephen Nutt: He didn't ask for a list. He asked for a number. That function returns the number of threads. Why do you need processes enumerated at all?
Billy ONeal
I am going to mark this one as the answer, assuming I understand what it says. Tell me if this is wrong. First I get an identifier for my process. (How?) Then I make an API call to get info on ALL the processes that are running. Then I look through it and find the identifier for my process. Once its found, I then go through a list of all the threads in my processes, counting as I go. As a penance for Lent, it is up to me to figure out how to do all that. Is that correct?
Jive Dadson
I believe PSAPI will give you the total number of threads on the machine, but not the total in your process. To get that number you need the ToolHelp API, and you can determine the number as you've outlined above. It is also possible to get the number directly with the performance counters, but I believe that is more complex in C/C++ (but easy using WMI from a script)
Stephen Nutt
A: 

Use a DLL that gets loaded early by your EXE. Counts the number of times DLL_THREAD_ATTACH and DLL_THREAD_DETACH are passed into your implementation of DllMain.

selbie
That is a cute suggestion and should work as long as DisableThreadLibraryCalls() has not been called in the process.
Anders