크리티컬 섹션 기본코드
typedef struct MSG_BLOCK_TAG {
CRITICAL_SECTION mGuard;
DWORD fReady, fStop;
volatile DWORD nCons, mSequence;
DWORD nLost;
time_t mTimestamp;
DWORD mChecksum;
DWORD mData[DATA_SIZE];
} MSG_BLOCK;
DWORD WINAPI Produce (void *arg)
{
srand ((DWORD)time(NULL));
while (!mBlock.fStop) {
Sleep(rand()/100);
EnterCriticalSection (&mBlock.mGuard);
__try {
if (!mBlock.fStop) {
mBlock.fReady = 0;
MessageFill (&mBlock);
mBlock.fReady = 1;
InterlockedIncrement (&mBlock.mSequence);
}
}
__finally { LeaveCriticalSection (&mBlock.mGuard); }
}
return 0;
}
DWORD WINAPI Consume (void *arg)
{
CHAR command, extra;
while (!mBlock.fStop) {
_tprintf (_T("\n**Enter 'c' for Consume; 's' to stop: "));
_tscanf (_T("%c%c"), &command, &extra);
if (command == _T('s')) {
mBlock.fStop = 1;
} else if (command == _T('c')) {
EnterCriticalSection (&mBlock.mGuard);
__try {
if (mBlock.fReady == 0)
_tprintf (_T("No new messages. Try again later\n"));
else {
MessageDisplay (&mBlock);
mBlock.nLost = mBlock.mSequence - mBlock.nCons + 1;
mBlock.fReady = 0;
InterlockedIncrement(&mBlock.nCons);
}
}
__finally { LeaveCriticalSection (&mBlock.mGuard); }
} else {
_tprintf (_T("Illegal command. Try again.\n"));
}
}
return 0;
}
'Research > Source Repository' 카테고리의 다른 글
| Variadic 매크로 (0) | 2014.06.16 |
|---|---|
| ThreadPool simple example (0) | 2013.11.03 |
| Mutex - Event Simple Code (0) | 2013.10.10 |
| [Source] Timep.c (0) | 2013.07.10 |
| Windows System Programming (0) | 2013.07.10 |