65.9K
CodeProject 正在变化。 阅读更多。
Home

高级关键部分

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.43/5 (4投票s)

2002年7月8日

viewsIcon

131321

downloadIcon

824

高级关键部分, 具有 TryLock 和超时功能。

引言

我需要一个易于使用且不依赖于 MFC 等库的临界区。此外,它应该适用于所有 Microsoft 操作系统,如 Win9x/Me、WinNT/2K/XP 和 PocketPC/CE 等。因此,我编写了一个名为 CriticalSection 的类,以满足我的需求。它实现了 LockUnlock 对象的功能(就像 Win32 临界区提供的那样)。但是,有两个特性是“普通”临界区所不具备的:

  • 一个带有可选超时的 Lock 函数
  • 一个在 Win9x/Me 操作系统上不可用的 TryLock 函数

操作

您可以从 CriticalSection 派生要同步的对象,或者将 CriticalSection 作为对象的一个成员。每当您进入需要保护的代码时,请调用临界区的 LockTryLock 函数。

请查看代码以了解其工作原理

// *******************************************************
// CriticalSection: Implements a critical section. 
// Provides a function similar to TryEnterCriticalSection 
// which is not available on Win9x/Me OSs
// *******************************************************
class CriticalSection  
{
public:
    // Construction/Destruction...
    CriticalSection();
    virtual ~CriticalSection();

    // Operations...
    // Locks this object. If another thread has ownership of 
    // this object the function waits
    //  until it's allowed to enter or the timeout elapses...
    inline bool Lock(const DWORD& dwMilliseconds = INFINITE)
    {
        if (::InterlockedCompareExchange(&m_lLockCount, 1, 0) == 0)
        {
            m_dwThreadID = ::GetCurrentThreadId();
            return true;
        }

        if (m_dwThreadID == ::GetCurrentThreadId())
        {
            ++m_lLockCount;
            return true;
        }

        if (::WaitForSingleObject(m_hEventUnlocked, 
            dwMilliseconds) == WAIT_OBJECT_0)
            return Lock(0);

        return false;
    }

    // Unlocks this object...
    inline void Unlock()
    {
        if (m_dwThreadID != ::GetCurrentThreadId())
            return;

        if (::InterlockedCompareExchange(&m_lLockCount, 0, 1) == 1)
        {
            m_dwThreadID = 0;
            ::PulseEvent(m_hEventUnlocked);
        }
        else
            --m_lLockCount;
    }

    // Tries to lock this object. 
    // If not applicable "false" is returns immediately...
    inline bool TryLock()
    {
        return Lock(0);
    }

private:
    // Internal data...
    DWORD m_dwThreadID;
    LONG m_lLockCount;
    HANDLE m_hEventUnlocked;

};

提供的示例应用程序将向您展示它的工作方式……

如果您需要帮助或有改进建议或发现错误,请随时给我发送电子邮件。更新版本可以在 www.nitrobit.comwww.codecommunity.com 上找到。

© . All rights reserved.