thread.h
来自「c++系统开发实例精粹内附的80例源代码 环境:windows2000,c++」· C头文件 代码 · 共 139 行
H
139 行
//////////////////////////////////////////////////////////////////////
// FileFury
// Copyright (c) 2000 Tenebril Incorporated
// All rights reserved.
//
// This source code is governed by the Tenebril open source
// license (http://www.tenebril.com/developers/opensource/license.html)
//
// For more information on this and other open source applications,
// visit the Tenebril OpenSource page:
// http://www.tenebril.com/developers/opensource
//
//////////////////////////////////////////////////////////////////////
#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 + =
减小字号Ctrl + -
显示快捷键?