Thread中分配的内存释放问题

Chice_wxg 2004-04-25 08:19:41
我的程序建立了一个thread,其中可能要执行一些阻塞的操作,比如阻塞的recv。同时也需要分配内存(比如用C的malloc和C++的new)来保存处理的数据。

但在主控thread中我想允许用户随时终止这个包含阻塞操作的thread,
如果用TheradTermine的话,显然在进行阻塞操作的thread中分配的内存得不到释放。


应该如何解决这个问题?谢谢!!
...全文
228 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
enoloo 2004-04-25
  • 打赏
  • 举报
回复
关于撤销资源,当线程被通知退出的时候,可以goto到某个撤销资源的地方。然后线程退出。
enoloo 2004-04-25
  • 打赏
  • 举报
回复
恩,向 shootingstars(有容乃大,无欲则刚)所说的,
将超时值指定小一点就可以了。可以在不同平台下指定

比如
#ifdef _WIN32_
TIMEOUT = 10;
#elif _LINUX
TIMEOUT = 20;
#...
#endif
shootingstars 2004-04-25
  • 打赏
  • 举报
回复
你把timeout设为10ms,用户的感觉应该是立即停止了。
在Windows系统中没有真正意义上的实时。
Chice_wxg 2004-04-25
  • 打赏
  • 举报
回复

比如用户要取消任务,那么就应该立刻终止thread。

而recv却要等待到timeout,实际thread被停止得晚了。

enoloo 2004-04-25
  • 打赏
  • 举报
回复
举个例子?

什么不可预测的阻塞?

可以在阻塞操作中插入线程通信,良好平台上的阻塞设计应该是可预测的,可控制的。一般都会提供超时值。

一点想法。
Chice_wxg 2004-04-25
  • 打赏
  • 举报
回复

还有啊,我希望用户的取消操作能立刻执行,也就是能否不等待timeout就终止thread并保证内存不泄露?

Chice_wxg 2004-04-25
  • 打赏
  • 举报
回复


谢谢 enoloo(行者无疆)


如果针对其他不可预测的阻塞不知道有没有更好的方法?

Chice_wxg 2004-04-25
  • 打赏
  • 举报
回复

其实我曾经设想用 垃圾收集 的方法实现,不过太过于复杂。

谢谢 jiangsheng(蒋晟.MSMVP2004Jan) ,

不过不知还有没有其他可行方案?


TO: rabo(闭关中...)
要跨平台,不能用MSC的函数

enoloo 2004-04-25
  • 打赏
  • 举报
回复
2,你的程序该怎么做:

在recv之前用while (GetMessage( lpMsg, hWnd, 0, 0)) ...
如果是WM_QUIT,GetMessage将返回false.这样作必要的清理,退出线程处理函数,或是直接用_endthreadex。

这样做得一个必要前提是,你的阻塞操作必须指定一个超时值,依你的程序而定。就是把一个阻塞操作分成几个部分,在里面插入消息循环。
enoloo 2004-04-25
  • 打赏
  • 举报
回复
关于PostThreadMessage,如果线程还没有消息队列(工作线程),那么用PostThreadMessage或者在线程中有GetMessage,PeekMessage等时,将会建立一个消息队列。

msdn:
The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use one of the following methods to handle this situation:

Call PostThreadMessage. If it fails, call the Sleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds.
Create an event object, then create the thread. Use the WaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage. In the thread to which the message will be posted, call PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE) to force the system to create the message queue. Set the event, to indicate that the thread is ready to receive posted messages.
rabo 2004-04-25
  • 打赏
  • 举报
回复
_endthread, _endthreadex
enoloo 2004-04-25
  • 打赏
  • 举报
回复
用消息,
BOOL PostThreadMessage(
DWORD idThread, // thread identifier
UINT Msg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);
指定Msg为WM_QUIT.

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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