(重要问题)专家们请帮忙解决一个正常杀死线程的问题!

KuangXiang 2000-08-10 05:21:00
各位专家好,这里有一个问题又要求教大家,请各位不吝赐教:
我写了个程序,为了该程序能更好的实现多线程功能,防止一些函数多线程运行时出现问题:
(1)我采用_beginthreadex()这个运行时函数来代替CreateThread()来创建多线程,因为_beginthreadex函数不但做了CreateThread做的全部功能,而且在多线程稳定性方面有明显的长处 !
(2)为了防止程序异常死掉,当我创建了一个线程的时候,我采用WaitForSingleObject函数来等待该线程运行一定的时间,如果到了规定的时间线程还没运行完,我就采用函数杀死这个没完成的线程,
那么现在的问题是:(1)当时间到了后线程却没执行完,我杀死这个线程,我用的是TerminateThread()函数,(不知道有没有和_beginthreadex()函数正好对应的终止线程的运行时函数而不是TerminateThread()函数)?
(2)当线程在规定的时间内没有执行完的话,我用终止线程函数来把他杀死,这样带来的问题是:如果线程中用到了某些资源的话,强行把线程杀死,很有可能存在内存泄露或者资源没有全部回收甚至是整个应用程序死掉,不知道各位专家对于我说的这个问题有什么好点的建议能确保程序稳定运行并且资源能正确回收,请指点,谢谢大家!

2000.8.10





...全文
345 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
panda_w 2000-12-30
  • 打赏
  • 举报
回复
同意kingwill的做法!
opkj 2000-08-11
  • 打赏
  • 举报
回复
如果线程正在访问oracle恐怕没那么简单!
kingwill 2000-08-11
  • 打赏
  • 举报
回复
其实解决的方法很简单。你只要先GetExitCodeThread()再CloseHandle()TerminateThread()。其中,CloseHandle()和TerminateThread()一定要配套使用。这样就可以释放资源。我试过,很好用的哦!
zzh 2000-08-11
  • 打赏
  • 举报
回复
一般终止线程是通过发消息 PostThreadMessage()来终止的,或者在线程中使用事件进行判断。当某一事件触发时,终止线程。这样资源就不会泄露了。
dannyxu 2000-08-11
  • 打赏
  • 举报
回复
下面的摘自msdn:
TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

If the target thread owns a critical section, the critical section will not be released.
If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
A thread cannot protect itself against TerminateThread, other than by controlling access to its handles.

从上文可以看出使用TerminateThread来强行停止一个线程是非常危险的,无法保证能够释放线程占用的资源。所以最安全的方法是在线程内部,或者是说由线程自己结束自己(可以使用_endthread或_endthreadex来安全地结束线程);或者是通过消息/事件等通知线程结束,例如PostThreadMessage,PostQuitMessage等。
「已注销」 2000-08-10
  • 打赏
  • 举报
回复
BOOL PostThreadMessage(

DWORD idThread, // thread identifier
UINT Msg, // message to post
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);
bbslucky 2000-08-10
  • 打赏
  • 举报
回复
terminalthread

15,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧