64,654
社区成员
发帖
与我相关
我的任务
分享
synchronized(syncObject) {
// code
}
struct Lock : CRITICAL_SECTION {
Lock() {
::InitializeCriticalSection(this);
}
~Lock() {
::DeleteCriticalSection(this);
}
void Enter() {
::EnterCriticalSection(this);
}
void Leave() {
::LeaveCriticalSection(this);
}
};
struct _auto_lock {
Lock& _lock;
_auto_lock(Lock& lock) : _lock(lock) {
_lock.Enter();
}
~_auto_lock() {
_lock.Leave();
}
};
Lock mylock;
void Test()
{
// code1 ...
// syn code
{
_auto_lock x(mylock);
}
// code2 ...
}
Lock mylock;
void Test()
{
// code1 ...
synchronized(mylock)
{
// sync code
}
// code2 ...
}
#define synchronized(lock) ..... _auto_lock _x(lock) ......
for(_auto_lock _x(mylock); ; )
for(int _i=0; _i<1; _i++)for(_auto_lock _x(mylock); _i<1; _i++)
#include <stdio.h>
#include <windows.h>
#include <process.h>
struct Lock : CRITICAL_SECTION {
Lock() {
::InitializeCriticalSection(this);
}
~Lock() {
::DeleteCriticalSection(this);
}
void Enter() {
::EnterCriticalSection(this);
}
void Leave() {
::LeaveCriticalSection(this);
}
};
struct _auto_lock {
Lock& _lock;
_auto_lock(Lock& lock) : _lock(lock) {
_lock.Enter();
}
~_auto_lock() {
_lock.Leave();
}
};
#define synchronized(lock) for(int _i=0; _i<1; _i++)for(_auto_lock _x(lock); _i<1; _i++)
// ---------- demo ----------
Lock mylock;
// ---------- test1 ----------
void WaitTest(int id)
{
printf("No.%d waiting...\n", id);
synchronized(mylock)
{
Sleep(1000);
}
printf("No.%d done\n", id);
}
void Test1()
{
_beginthread((void(__cdecl*)(void*))WaitTest, 0, (void*) 1);
_beginthread((void(__cdecl*)(void*))WaitTest, 0, (void*) 2);
_beginthread((void(__cdecl*)(void*))WaitTest, 0, (void*) 3);
}
// ---------- test2 ----------
void ThrowFunc(int id)
{
printf("No.%d waiting...\n", id);
synchronized(mylock)
{
Sleep(1000);
throw "some err";
}
printf("No.%d done\n", id);
}
void ThrowTest(int id)
{
try
{
ThrowFunc(id);
}
catch(...)
{
printf("%d excepted\n", id);
}
}
void Test2()
{
_beginthread((void(__cdecl*)(void*))ThrowTest, 0, (void*) 1);
_beginthread((void(__cdecl*)(void*))ThrowTest, 0, (void*) 2);
_beginthread((void(__cdecl*)(void*))ThrowTest, 0, (void*) 3);
}
// ---------- test3 ----------
void BreakTest(int id)
{
printf("No.%d waiting...\n", id);
synchronized(mylock)
{
Sleep(1000);
break;
Sleep(99999999);
}
printf("No.%d done\n", id);
}
void Test3()
{
_beginthread((void(__cdecl*)(void*))BreakTest, 0, (void*) 1);
_beginthread((void(__cdecl*)(void*))BreakTest, 0, (void*) 2);
_beginthread((void(__cdecl*)(void*))BreakTest, 0, (void*) 3);
}
int main(int argc, char* argv[])
{
printf("Wait Test. Press any key to start...\n");
getchar();
Test1();
getchar();
printf("Exception Test. Press any key to start...\n");
getchar();
Test2();
getchar();
printf("Break Test. Press any key to start...\n");
getchar();
Test3();
getchar();
return 0;
}