/******************************************************************************
Module:  SchedLab.cpp
Notices: Copyright (c) 2000 Jeffrey Richter
******************************************************************************/
#include "..\CmnHdr.h"     /* See Appendix A. */
#include <windowsx.h>
#include <tchar.h>
#include <process.h>       // For _beginthreadex
#include "Resource.h"
///////////////////////////////////////////////////////////////////////////////
DWORD WINAPI ThreadFunc(PVOID pvParam) 
{
   HANDLE hThreadPrimary = (HANDLE) pvParam;
   SuspendThread(hThreadPrimary);
   chMB(
      "The Primary thread is suspended.\n"
      "It no longer responds to input and produces no output.\n"
      "Press OK to resume the primary thread & exit this secondary thread.\n");
   ResumeThread(hThreadPrimary);
   CloseHandle(hThreadPrimary);   // To avoid deadlock, call EnableWindow after ResumeThread.
   EnableWindow(GetDlgItem(FindWindow(NULL, TEXT("Scheduling Lab")), IDC_SUSPEND), TRUE);
   return(0);
}以上这段代码是《windows核心编程》第7章SchedLab.cpp 中第1到30行的代码。他为什么说EnableWindow()这个函数能防止死锁?

解决方案 »

  1.   

    没看过,不过根据Press OK to resume the primary thread & exit this secondary thread应该是之前已经把标题为"Scheduling Lab"的窗口 disable 掉,enable 它只是为了能继续操作。
      

  2.   

    你要看全部的代码.
    他这么做使得IDC_SUSPEND这个按钮可用,
    用户单击这个按钮时,程序可以改变线程的执行情况.
    你重点要看IDC_SUSPEND函数里的代码
    注:我没看过《windows核心编程>>只是自己猜想的
      

  3.   

    没看过这个程序,我也来猜一下,
    这里肯定是要激活EnableWindow的控件,那个控件肯定是能让程序正常运行下去的关键,如果退出这个线程
    那个控件还没激活就死在那了。
    我觉得这里用死锁应该不准确。
      

  4.   

    当SuspendThread调用时,被挂起的线程可能在进行某种操作,如果它占用了某资源,windows会给它所占用的资源上锁,这样其他线程如果要访问这些资源就会等待。
    在IDC_SUSPEND的处理逻辑中,调用EnableWindow将主窗口——也就是主线程所对应的窗口disable掉了,也就是说这样确保主UI线程从按下IDC_SUSPEND到被挂起之前,用户都不能进行任何操作,确保它在挂起时,是一个干净的状态。
      

  5.   

    EnableWindow是一个带返回值的消息发送函数。子线程ThreadFunc发送消息给主线程,然后子线程被挂起(因为Windows的消息处理机制导致),等待主线程返回处理消息的返回值。但是主线程又被子线程暂停结果两个线程全部被挂起。这是Windows处理消息机制的一个缺陷。你看到26章就明白了。