#pragma once #include <windows.h> //使用臨界區作的鎖 //做用:可被第三方聚合,進行同步處理 class CLock { CRITICAL_SECTION m_sec; public: CLock() { ::InitializeCriticalSection(&m_sec); } virtual ~CLock() { ::DeleteCriticalSection(&m_sec); } void Lock() { ::EnterCriticalSection(&m_sec); } void UnLock() { ::LeaveCriticalSection(&m_sec); } }; //使用臨界區 鎖定 //供安全類型模板類使用 class CCSLock { CRITICAL_SECTION& m_sec; public: //從臨界區引用建立 CCSLock(CRITICAL_SECTION &sec) : m_sec(sec) { Lock(); } ~CCSLock() { UnLock(); } void Lock() { ::EnterCriticalSection(&m_sec); } void UnLock() { ::LeaveCriticalSection(&m_sec); } }; //安全類型模板類 //能夠經過模板函數封裝出類型安全的整數,枚舉等簡單變量 template<typename T> class CSafeType { private: CRITICAL_SECTION m_sec; public: CSafeType() { ::InitializeCriticalSection(&m_sec); } virtual ~CSafeType() { ::DeleteCriticalSection(&m_sec); } void WaitUnitl(T t) { while(true) { CCSLock tempVal(m_sec); if(m_data== t) break; Sleep(10); } } operator T() { CCSLock tempVal(m_sec); return (m_data); } T operator =(T& t) { CCSLock tempVal(m_sec); m_data = t; return m_data; } T operator =(const T& t) { CCSLock tempVal(m_sec); m_data = t; return m_data; } bool operator ==(T t) { CCSLock tempVal(m_sec); return m_data == t; } bool operator !=(T t) { CCSLock tempVal(m_sec); return m_data != t; } bool operator <(T t) { CCSLock tempVal(m_sec); return m_data < t; } bool operator <=(T t) { CCSLock tempVal(m_sec); return m_data <= t; } bool operator >(T t) { CCSLock tempVal(m_sec); return m_data > t; } bool operator >=(T t) { CCSLock tempVal(m_sec); return m_data >= t; } T m_data; };
其中,對於CSafeType使用下面提供一個不怎麼好的例子:ios
#include "Locker.h" #include <iostream> #include<conio.h> #include <windows.h> using namespace std; CSafeType<DWORD> testData; DWORD WINAPI WriteData(void *p) { while(1) { testData = GetTickCount(); Sleep(1); } return 0; } DWORD WINAPI ReadData(void *p) { while(1) { cout<<testData<<endl; Sleep(1); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { HANDLE hWrite, hRead; DWORD dwWrite, dwRead; hWrite = CreateThread(NULL, 0, WriteData, NULL, 0, &dwWrite); hRead = CreateThread(NULL, 0, ReadData, NULL, 0, &dwRead); while(!_kbhit()) Sleep(10); CloseHandle(hWrite); CloseHandle(hRead); return 0; }
但願哪位高人給出更能說明CSafeType做用的使用例子,謝謝!windows