⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 thread.h

📁 主动对象模式的实现
💻 H
字号:
#if !defined THREAD_H
#define THREAD_H
//------------------------------------
//  (c) Reliable Software, 1997
//------------------------------------

#include <windows.h>

class Thread
{
public:
    Thread ( DWORD (WINAPI * pFun) (void* arg), void* pArg)
    {
        _handle = CreateThread (
            0, // Security attributes
            0, // Stack size
            pFun, 
            pArg, 
            CREATE_SUSPENDED, 
            &_tid);
    }
    ~Thread () { CloseHandle (_handle); }
    void Resume () { ResumeThread (_handle); }
    void WaitForDeath ()
    {
        WaitForSingleObject (_handle, 2000);
    }
private:
    HANDLE _handle;
    DWORD  _tid;     // thread id
};

class Mutex
{
    friend class Lock;
public:
    Mutex () { InitializeCriticalSection (&_critSection); }
    ~Mutex () { DeleteCriticalSection (&_critSection); }
private:
    void Acquire () 
    { 
        EnterCriticalSection (&_critSection);
    }
    void Release () 
    { 
        LeaveCriticalSection (&_critSection);
    }

    CRITICAL_SECTION _critSection;
};

class Lock 
{
public:
	// Acquire the state of the semaphore
	Lock ( Mutex& mutex ) 
		: _mutex(mutex) 
	{
		_mutex.Acquire();
	}
	// Release the state of the semaphore
	~Lock ()
	{
		_mutex.Release();
	}
private:
	Mutex& _mutex;
};

class Event
{
public:
    Event ()
    {
        // start in non-signaled state (red light)
        _handle = CreateEvent (0, TRUE, FALSE, 0);
    }

    ~Event ()
    {
        CloseHandle (_handle);
    }

    // put into signaled state
    void GreenLight () { SetEvent (_handle); }
    // put into non-signaled state
    void RedLight () { ResetEvent (_handle); }
    void Wait ()
    {
        // Wait until event is in signaled (green) state
        WaitForSingleObject(_handle, INFINITE);
    }

private:
    HANDLE _handle;
};

class AtomicCounter
{
public:
    AtomicCounter () : _counter(0) {}

    long Inc ()
    {
        // Return the sign (or zero) of the new value
        return InterlockedIncrement (&_counter);
    }

    long Dec ()
    {
        // Return the sign (or zero) of the new value
        return InterlockedDecrement (&_counter);
    }

    BOOL IsNonZeroReset ()
    {
        return InterlockedExchange (&_counter, 0) != 0;
    }
  
private:
    long _counter;
};

#endif

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -