-
SpinLockOperations Dev/writech 2010. 12. 10. 18:22
// Example05_SpinLock.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
// 커널모르게 돌리면 유저모드#include "stdafx.h"
#include<windows.h>
#include<process.h>#include<string>
#include<iostream>
using namespace std;unsigned int WINAPI writeCharacter(LPVOID param);
string g_string;
int const MAX_THREAD = 5;
bool g_isLocked = false;int _tmain(int argc, _TCHAR* argv[])
{
DWORD threadIDs[MAX_THREAD];
HANDLE threadHandles[MAX_THREAD];
char alphas[MAX_THREAD];for(int i =0; i<MAX_THREAD; ++i)
{
alphas[i] = 'a' + i;threadHandles[i] = (HANDLE) ::_beginthreadex( NULL, 0 , writeCharacter,(LPVOID*)(&alphas[i]),0,(unsigned int *)&threadIDs[i]);
}
DWORD result = ::WaitForMultipleObjects(MAX_THREAD, &threadHandles[0],TRUE,INFINITE);
if(result == WAIT_OBJECT_0)
{
cout<<g_string;
}
for(int i = 0; i< MAX_THREAD; ++i)
{
CloseHandle(threadHandles[i]);
}return 0;
}unsigned int WINAPI writeCharacter(LPVOID param)
{
char ch = *((char *)param);
while(g_isLocked);
g_isLocked = true; //이곳에서 ContextSwitching이 일어나면 위의 while문에서 뻑날수있다. 원자적연산이 아니기때문에.
/***************임계영역 *************************/
for(int i = 0; i< 1000; ++i)
{
g_string += ch;
}
/**************************************************/
g_isLocked = false;
return 0;
}
'Operations Dev > writech' 카테고리의 다른 글
Mutex (0) 2010.12.10 Semaphore (0) 2010.12.10 CriticalSection (0) 2010.12.10 SpinLock2 (0) 2010.12.10 SimpleConcurrency (0) 2010.12.10