问题描述
场景:
1.)具有长度为4的布尔数组.
2.)我在函数1中创建了一个线程来执行函数3
3.)我有一个函数2删除布尔数组
如果删除布尔数组,如何停止执行function3的任何现有线程?
Scenario:
1.)Have a boolean array of length 4.
2.)I have a thread that is created in function 1 to execute function 3
3.)I have a function 2 that deletes the boolean array
how do i stop any existing threads from executing function3 if boolean array is deleted?
public:
function 1
function 2
function 3
bool bArray[4];
Handle mainHandle;
function1()//called for every one second until DestroyTimer() is called
{
mainHandle = CreateThread(NULL, 0, ::function3, this, 0, NULL);
}
function3()
{
bArray[2] = false;
}
function2()
{
DestroyTimer();
bArray = NULL;
//here comes the problem, event though i called destroy timer there are threads that are already created and when they execute function3 they throw an assertion that bArray is NULL.
}
因此要解决这个问题.在删除bArray之前,我要终止或暂停任何现有线程,我需要对该线程进行处理.我如何暂停或停止执行线程?
So to solve this. Before deleting bArray i want to terminate or suspend any existing threads, i have the Handle to the thread. how do i suspend or stop the thread from executing?
推荐答案
function3()
{
while (!bExitThread)
{
doSomething();
}
};
您可以对此进行一些修改:
You could modify this a bit:
function3()
{
while (!bExitThread)
{
if (!bSuspended)
{
doSomething();
}
else
{
Sleep(100); // avoid busy waiting
}
}
}
现在您可以:
1)通过将bExitThread设置为TRUE
使线程干净退出2)通过将bSuspended设置为TRUE来使线程被挂起",而不会破坏底层的OS线程(您可以通过将bSuspended设置为FALSE来再次恢复它)
Now you can:
1) Make thread exit cleanly by setting bExitThread to TRUE
2) Make thread "suspended" by setting bSuspended to TRUE without destroying the underlying OS thread (and you can resume it again by setting bSuspended to FALSE)
这篇关于如何停止执行已创建的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!