如果有与休眠并行的操作,比如下面程序中对ret赋值,那么这个并行的操作在什么时候被执行呢?而且,执行SuspendThread后,线程是立刻进入休眠的么?如果这么做(在线程内休眠自己,在线程外重新启动),有没有什么副作用?谢谢各位。#include <windows.h>
#include <iostream>using std::cin;
using std::cout;
using std::endl;DWORD ret = -1;
HANDLE threadHandle = 0;DWORD WINAPI ThreadProc(LPVOID lpParam)
{
::Sleep(500);
cout<<"123"<<endl;
DWORD ret = ::SuspendThread(threadHandle);//程序运行到这里时,会休眠自己,那么ret会在什么时候被赋值呢?休眠前还是休眠后?为什么?
while(1)
cout<<"abc"<<endl;
return 0;
}int _tmain(int argc, _TCHAR* argv[])
{
DWORD a;
threadHandle = ::CreateThread(NULL, 0, ThreadProc, 0, 0, &a);
::Sleep(1000);
::Sleep(1000);
a = ::ResumeThread(threadHandle);
::Sleep(1000);
return 0;
}

解决方案 »

  1.   

    SuspendThread在休眠后才返回。你看看汇编码就知道了
      

  2.   

    那我如何知道线程是否成功休眠呢?还有,是调用Suspend后,线程就立刻进入休眠状态么?还是会有一段不定的等待时间?
      

  3.   

    Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself.
      

  4.   

    jiangsheng兄,如果没有同步对象的存在,是不是这样就是安全的?还有个问题,线程池一般是如何实现的?我的想法是起一系列的休眠线程,然后在需要用到时替换内部的运行函数,这个函数运行完后,线程将设标志位标志回收,并自己休眠自己,不知道这样是否可行。
      

  5.   

    1 hard to say. deadlock can occur in other conditional waitings
    2 http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/vcsample/html/vcsamCThreadPoolSample.asp