如何安全地关闭包含无限循环的线程 [英] How to safely close a THREAD which has a infinite loop in it

查看:73
本文介绍了如何安全地关闭包含无限循环的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 _beginthreadex 函数创建一个线程.我传入的函数地址有一个无限的 while 循环 (while(1)) .我有 threadidthreadhandle.

I am creating a thread using _beginthreadex function. The function address I am passing in it has an infinite while loop (while(1)) . I have the threadid and threadhandle.

我可以使用 TerminateThread(threadhandle,1); 但它很危险.

I can use TerminateThread(threadhandle,1); But it is dangerous.

安全的方法是使用_endthreadex杀死线程,但它只能从线程内部使用,我想从外部杀死线程.

The safe way is to kill thread using _endthreadex but it can only be used from inside the thread, and I wanted to kill the thread from outside.

所以请建议是否有一种安全的方法可以使用 threadidthreadhandle 从外部安全地关闭、结束或终止线程.

So please suggest if there is a safe way to close,end or kill the thread safely from outside using threadid or threadhandle.

推荐答案

你应该——字面意思——永远不要使用TerminateThread().我什至不是在开玩笑.如果你从外部终止一个线程,它里面保留的所有资源都会被泄露,内部访问的所有状态变量都会有一个未确定的状态等等.

You should - literally - never use TerminateThread(). And I'm not even joking. If you are terminating a thread from the outside, all resources reserved in it will be leaked, all state variables accessed inside will have an undetermined state and so on.

您的问题的解决方案可能是让您的线程自行完成.它可以通过线程安全方式更改的 volatile 变量(参见 InterlockedIncrement())、Windows 事件或类似的东西来完成.如果您的线程有消息循环,您甚至可以通过发送消息要求它停止来实现.

The solution for your problem might be signaling your thread to finish itself. It can be done by a volatile variable changed by thread-safe means (see InterlockedIncrement() on that), a Windows event, or something like that. If your thread has a message loop you can even do it by sending a message to ask it to stop.

这篇关于如何安全地关闭包含无限循环的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆