这两个函数都有一个BOOL返回值,我不知道他们的含义。什么情况下会返回FALSE?
我理解是这样的:
CCriticalSection cs;
int i;//share data
线程a:
1:cs.Lock();
2:i=0;
3:cs.Unlock();
线程b:
BOOL result=TRUE;
result=cs.Lock();是否当线程a执行到第2行时,线程b开始执行cs.Lock(),这时result得到的返回值为FALSE?
不知道是不是这样的?

解决方案 »

  1.   

    CCriticalSection::LockReturn Value
    Nonzero if the function was successful; otherwise 0.CCriticalSection::UnlockReturn Value
    Nonzero if the CCriticalSection object was owned by the thread and the release was successful; otherwise 0.
    msdn上有,何必问
      

  2.   

    Nonzero if the function was successful; otherwise 0.
    这样的解释是不是太笼统了些,我想知道是什么原因导致
    function was not successful!因为我连续调用
    result1=cs.Lock();
    result2=cs.Lock();
    而两个返回值都是TRUE.
      

  3.   

    After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns.
      

  4.   

    看看MSDN上
    EnterCriticalSection
    函数
    的说明中的Res
      

  5.   

    这两个函数基本不会返回 FALSE,在 VC6 自带的 MFC 代码是这样写的:_AFXMT_INLINE BOOL CCriticalSection::Lock()
    { ::EnterCriticalSection(&m_sect); return TRUE; }
    _AFXMT_INLINE BOOL CCriticalSection::Unlock()
    { ::LeaveCriticalSection(&m_sect); return TRUE; } 但是内存不足的情况下,EnterCriticalSection 有可能产生 Code 为 EXCEPTION_INVALID_HANDLE 的异常(创建 Event 失败)。
      

  6.   

    谢谢两位!
    我原以为可以通过lock的返回值来判断是线程a否有占用着共享数据。看来不是这样的。
    那是不是有这样的机制,可以知道线程a是否正占用着共享数据呢。(不过想想,这可能的是多余的功能吧,因为线程a如果真占用着共享数据,那线程b肯定会阻塞的。知不知道无所谓。)
      

  7.   

    TryEnterCriticalSection 可以用于检查共享数据是否可用,如果数据被占用,它直接返回 FALSE。