//通过定义锁类,不用手动释放TCriticalSection指针
//这样定义锁变量,MyLocker lock1;
//在需要保护的资源前,lock1.Enter();
//资源使用完毕,lock1.Leave();
//本文在c++ builer 10.3 32/64位,及6.0版本调试通过。
#if(__BORLANDC__<=1380) // 低版本
#include <vcl.h>
#include <SyncObjs.hpp>
#else
#include <System.SyncObjs.hpp>
#endif
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
class MyLocker
{private:
TCriticalSection *pLocker;
public:
MyLocker()
{pLocker=new TCriticalSection();
}
~MyLocker()
{delete pLocker;
}
void Enter()
{pLocker->Enter();
}
void Leave()
{pLocker->Leave();
}
void Lock()
{Enter();
}
void UnLock()
{Leave();
}
};
const unsigned int THREAD_NUM = 50;
unsigned int g_Count = 0;
MyLocker lock1;
DWORD WINAPI ThreadFunc(LPVOID);
#if(__BORLANDC__<=1380) // 低版本
int main(int argc, char* argv[])
#else //高版本
int _tmain(int argc, _TCHAR* argv[])
#endif
{ HANDLE hThread[THREAD_NUM];
for (int i = 0; i < THREAD_NUM; i++)
{hThread[i] = CreateThread(NULL, 0, ThreadFunc, 0, 0, NULL); // 创建线程
}
WaitForMultipleObjects(THREAD_NUM, hThread, true, INFINITE); //等到所有子线程都返回
system("pause");
return 0;
}
DWORD WINAPI ThreadFunc(LPVOID p)
{ lock1.Enter(); // 进入关键段
printf("%d\n",g_Count);
g_Count++;
lock1.Leave();
return 0;
}