in general, this class is normal.but i write a counter in Run(), and Set counter to a window text.following code show this:
int i = 0;
wsprintf(buf, "%d", i);
but i only write OutputDebugString instead of SetWindowText,
it is can exit normally. why?
I had the same problem, with a multithreaded program,
and used the returned handle from CreateThread, as well
as the ThreadID to track the threads. I saved them in an
array ( DWORD, same as Hndl ), and passed the thread
an index to this array in the lpParameter.
The threads can then identify themselves, and the
controlling program can access each thread using the
thread handle and/or threadID
If a thread is terminated by TerminateThread(), The stack for that particular thread os released only when the process that owns it is terminated. This could also lead to access violation due to the following reasons
Some other thread might still be using pointers that reference data contained on the terminated thread's stack, if these other threads attempted to access the stack, an access violation could occur.
For more details kindly refer the book
"Advanced Windows Third Edition" by Jeffrey Richter
What happens if CreateNewThread is called more than once ? I would suggest that the thread creation be done in the constructor. The thread should be created in suspended mode, this is to ensure that the virtual functions don't get invoked before the construction of the object is completed. The user has to call Resume after constructing the object.
There needs to be a mechanism to inform the thread to exit gracefully. You can add a manual reset event to the base class which can be checked in the Run method of the derived class. Provide a Shutdown method in the base class which will set this event.
With these additions the user code will look like this
CMythread thread; // Derived from ThreadClass
thread.Resume(); // Activate the thread
// Time to shutdown, inform the thread to stop