I have a very strange error in my multithreaded application. The situation is as follows:
I have one dialog window open, this dialog spawns 2 threads (thread 2, thread 3] when it is initialized.
This thread spawns two other threads (thread 4, thread 5). After spawning those threads, it retrieves data from a buffer
The two other threads are identical and retrieve data from 2 diffenrent COMM ports and put the data in the buffer.
When data is successfully retrieved, it notifies thead 3.
Before shutting down, it notifies the monitor thread (3) and shuts down thread 4 and 5. It waits until the threads are cleaned up.
Its sole purpose is to monitor thread 2 and notify the dialog when data is arrived.
This thread cleans up itself after it recieved the notification that thread 2 is stopped.
[thread 3, thread 4]
These two threads retrieve data from two different COMM ports. The retrieved data is stored in a std::vector managed by thread 2.
You may think that I have too much thread for this purpose (2 would be enough for this type of work), but this is by design. The extra monitor thread is used because this is a test application. In the real application the monitor threads do some real work.
Now for the problem. Everything works like a charm, except when I try to stop thread 2. It actually manages to stop thread 3 and 4. After that, the thread is cleaned up (the thread 2 and 3 are gone in PView thread 2 not). But then, BANG the program crashes in the middle of the following function:
AfxUnlockTempMaps at the following line:
pThreadState->m_pSafetyPoolBuffer = malloc(pApp->m_nSafetyPoolSize);
The error message in the output window of VS2005 is:
Unhandled exception at 0x02845922 (dbghelp.dll) in TestInput.exe: 0xC0000005: Access violation reading location 0x0152070c.
The location is always the same and no pointer is even near that address...
I noticed that the problem does not occur when thread 3 and 4 stop sending data to the buffer of thread 2. Here are some code snippets:
The call where the data is added to the buffer of thread 2
The AddDataToInternalBuffer function
void AddDataToInternalBuffer(SERIAL_DATA& SerialData)
Does anybody have a clue what might be happening?