调试与编译多线程中线程句柄的cwinthread的问题
我有三个一种类型的对象,形成一个类,现在将三个类分别创建并存入到vector中,类有两个线程,三个共有六个线程,三个对象分别独立动作,类中用静态函数声明两个cwinthread线程对象m_psl,m_pxl,并在类构造时创建了,然后在类的一个函数中判断m_psl,m_pxl是否仍在运行,如果不在运行状态,则执行线程,现在的问题是:在debug时各动作可正确执行,在release时当执行完成一次各个线程后,再执行其中任一个线程,判断其它的线程则都在执行状态,用GetExitCodeThread来判断的。
请同聊们指教。
[解决办法]
你是怎么判断是否thread真的在运行的?
正常情况应该不会出现这个问题啊,除非你的判断方式不够好
建议用以下办法:
class mythread
{
mythread() { m_isrunning = false; ......}
...
private:
WINAPI ThreadProc(void *lparam);
bool m_isrunning; //是否正在运行
};
WINAPI ThreadProc(void *lparam)
{
mythread *pThis = (mythread*) lparam;
pThis-> m_isrunning = true; //标记开始运行
Do something...
pThis-> m_isrunning = false; //标记线程结束
}
[解决办法]
是否出现内存泄露,取决于你内存释放的方式
一般来说,你线程中申请的内存就在线程中释放,其它地方尽量少访问,就不会发生泄露
至于线程的释放,这个更没必要担心了,这是操作系统的事情,线程的函数执行完毕,你就完全可以不管它了
[解决办法]
To make sure your threads is terminated properly
1 create the thread suspended
2 create two manual signaled Windows event (CreateEvent) in the thread, one for external termination, one for thread status
3 set m_bAutoDelete to false after AfxBeginThread
4 make a call to resume the thread
5 in your thread, write code to check the state of the external termination event. If it is signaled, quit the thread as soon as possible. For a worker thread, don 't make a block call. Add a timeout so you can exiting the loop in time. For a UI thread, call AfxEndThread().
6 in your thread, write code to change the state of the thread status event. For a worker thread, put it at the end of the thread function. For a UI thread, override CWinThread::Delete().
7 in your main window, handle WM_DESTROY and write code to change the state of the external termination event Before your CWnd::OnDestroy call.
8 In the same function, start a loop to check the state of the thread status event. Use MsgWaitForMultipleObjects if you have many threads. Use Sleep() or dispatch messages to wait for ohher threads.
[解决办法]
你是怎么判断是否thread真的在运行的?
正常情况应该不会出现这个问题啊,除非你的判断方式不够好
建议用以下办法:
class mythread
{
mythread() { m_isrunning = false; ......}
...
private:
WINAPI ThreadProc(void *lparam);
bool m_isrunning; //是否正在运行
};
WINAPI ThreadProc(void *lparam)
{
mythread *pThis = (mythread*) lparam;
pThis-> m_isrunning = true; //标记开始运行
Do something...
pThis-> m_isrunning = false; //标记线程结束
}