本文介绍了为什么该程序没有结束创建的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
下面的简单程序将使用CreateThread API创建两个线程,然后根据简单标志从该线程简单地返回,但是如果我在进程资源管理器中查看句柄,则创建的两个线程将不会结束

hi all,
the simple program below will create two threads using CreateThread API and then simply returns from the thread depending on the simple flag but two thread created will not be ended if i view the handles in process explorer

<br />
<br />
bool killthread1 = false,killthread2=false;<br />
void thread1()<br />
{<br />
        while(1)<br />
	{<br />
		if (killthread1)<br />
		{<br />
			printf("thread1 killed\n");<br />
			return;<br />
		}<br />
	}<br />
}<br />
<br />
void thread2()<br />
{<br />
	while(1)<br />
	{<br />
		if (killthread2)<br />
		{<br />
			printf("thread2 killed\n");<br />
			return;<br />
		}<br />
	}<br />
}<br />
<br />
int _tmain(int argc, _TCHAR* argv[])<br />
{<br />
	HANDLE th1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(thread1),NULL,0,0);<br />
	HANDLE th2 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(thread2),NULL,0,0);<br />
	getch();<br />
	killthread1=killthread2=true;<br />
	getch();<br />
	return 0;<br />
}<br />



在调试模式下,visual studio显示2个线程在执行返回0之前已结束,但是进程资源管理器"显示它们仍处于活动状态,这是怎么回事?



In debug mode visual studio shows that 2 threads are ended before executing return 0, but "process explorer" shows they are alive, what is wrong in this??

推荐答案

写道:​​

bool killthread1 = false,killthread2 = false;

bool killthread1 = false,killthread2=false;





写道:​​

但如果我在进程浏览器中查看句柄,创建的两个线程将不会结束

but two thread created will not be ended if i view the handles in process explorer



这是因为用于检查线程终止条件的标志未声明为volatile.

因此,优化器必须完全删除支票!

请阅读以下内容: http://www.flounder.com/workerthreads.htm [ ^ ]



This is because the flags that you''re using to check for the thread termination condition is NOT declared as volatile.

Therefore, the optimiser must have completely removed the check!

Please read this: http://www.flounder.com/workerthreads.htm[^]




这篇关于为什么该程序没有结束创建的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:15