0

I have a multithreaded application in C++ for Windows 7. This app is compiled as a DLL for the use of another C# app.

I run the multithreaded code for long hours to process streaming data. If I compile this C++ code into a stand-alone .exe, and run the code, it works fine.

But when it is turned into a DLL and when the C# code runs with it, the program crashes with Access Violation error after long runs. I see a similar crash when I load the DLL from a Python script and run it for long hours.

When I watch the behavior using Task Manager, I see the System Handle count increasing at a really rapid pace. After around 2 hours of code run, i see the handle count cross 300,000 mark and it keeps increasing.

Inside the multithreaded code, the threads are being created and teared down continuously. I see that after the thread is exited, the thread handle is not closed explicitly by an CloseHandle function. Could this be a potential problem?

How do I confirm that it is a handles issue. What are the ways to watch these system resources in a better way? Before I attempt any fixes, I would like to know all possible solutions as the test runs take a long time, more than 5 hours, to reproduce the crash.

Kamalakshi
  • 6,918
  • 3
  • 17
  • 21
  • According to [MSDN](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682453(v=vs.85).aspx): _The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle._ – 001 Apr 12 '14 at 01:24
  • 1
    Since you're asking for recommendations on a tool, your question is likely to get closed. You might want to edit it to refocus on what the cause is rather than tools to find it. In the meantime, a handle leak could definitely pose a problem since resources get released by Windows when the process ends, not when the DLL is unloaded. – Carey Gregory Apr 12 '14 at 01:25
  • If the handle is not being closed at some point - either after the thread has been created or when it is closed - then that is definitely a bug and certainly could explain your symptoms. I'd fix the bug first, if I were you, and only worry about further troubleshooting if the symptoms continue. – Harry Johnston Apr 12 '14 at 03:08

1 Answers1

1

SysInternals Process Explorer can view the handles in a process and identify them as thread, mutex, file, etc. handles. You definitely have to CloseHandle() each thread handle to clean them up.

As an aside, creating a thread is an expensive operation. If you are creating a lot of thread jobs, it is better to queue the jobs and create a pool of a limited number of threads (usually about equal to the number of CPUs in the system) that pull from the queue and perform the job.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251