CCriticalSection::Lock

调用该成员函数对临界区对象的访问权。

BOOL Lock( ); 
BOOL Lock(
   DWORD dwTimeout 
);

参数

  • dwTimeout
    Lock 忽略此参数值。

返回值

非零,如果函数运行成功;否则为0。

备注

Lock 不会返回的阻塞调用,直到临界区对象收到信号(变为可用)。

如果计时等待有必要,可以使用 CMutex 对象而不是 CCriticalSection 对象。

如果 Lock 不能分配必要的系统内存,内存异常(类型 CMemoryException)自动将引发。

示例

此示例通过控制对共享资源(静态 _strShared 对象)的访问演示嵌套的临界区方法使用共享 CCriticalSection 对象。 SomeMethod 函数来演示更新共享资源以安全的方式。

//Definition of critical section class
class CMyCritSectClass
{
   static CString _strShared; //shared resource
   static CCriticalSection _critSect;
public:
   CMyCritSectClass(void) {}
   ~CMyCritSectClass(void) {}
   void SomeMethod(void); //locks, modifies, and unlocks shared resource
};

//Declaration of static members and SomeMethod
CString CMyCritSectClass::_strShared;
CCriticalSection CMyCritSectClass::_critSect;

void CMyCritSectClass::SomeMethod()
{
   _critSect.Lock();
   if (_strShared == "")
      _strShared = "<text>";
   _critSect.Unlock();
}

要求

Header: afxmt.h

请参见

参考

CCriticalSection选件类

层次结构图

CSingleLock::Lock