// spinlock.cpp : Defines the entry point for the console application.
//
// By Kyungmin Cho, bro@shinbiro.com
// 2006/07/28 http://neri.cafe24.com
//
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>
typedef struct _spinlock
{
int lock;
}spinlock;
void spin_lock_init( spinlock* s )
{
s->lock = 1; // unlocked.
}
int test_and_set( int* val, int newval )
{
int prev;
__asm
{
mov eax, newval
mov ebx, val
xchg eax, [ebx] // 모든 코어에 대해 상호배재임. lock; prefix없어도 됨
mov prev, eax
}
return prev;
}
void spin_lock( spinlock* s )
{
int prev = 0;
int* plock = &s->lock;
do
{
// set s = 0 (lock)
prev = test_and_set( &s->lock, 0 );
if( s->lock == 0 && prev == 1 )
break;
}while(1);
}
void spin_unlock( spinlock* s )
{
test_and_set( &s->lock, 1 ); // unlock
}
// spin lock 획득 가능한가 한번 시도해보고 바로 리턴
int spin_lock_try( spinlock* s )
{
int prev;
prev = test_and_set( &s->lock, 0 );
if( s->lock == 0 && prev == 1 )
return 1; // spin lock 획득!
return 0; // 획득 실패
}
spinlock s;
void task1(void*)
{
spin_lock( &s );
printf("[task1] ok! \n");
Sleep(1000);
printf("[task1] somthing! \n");
spin_unlock( &s );
}
void task2(void*)
{
spin_lock( &s );
printf("[task2] ok! \n");
Sleep(1000);
printf("[task2] somthing! \n");
spin_unlock( &s );
}
int main(int argc, char* argv[])
{
s.lock = 1;
_beginthread( task1, 0, 0 );
_beginthread( task2, 0, 0 );
getch();
return 0;
}
//
// By Kyungmin Cho, bro@shinbiro.com
// 2006/07/28 http://neri.cafe24.com
//
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>
typedef struct _spinlock
{
int lock;
}spinlock;
void spin_lock_init( spinlock* s )
{
s->lock = 1; // unlocked.
}
int test_and_set( int* val, int newval )
{
int prev;
__asm
{
mov eax, newval
mov ebx, val
xchg eax, [ebx] // 모든 코어에 대해 상호배재임. lock; prefix없어도 됨
mov prev, eax
}
return prev;
}
void spin_lock( spinlock* s )
{
int prev = 0;
int* plock = &s->lock;
do
{
// set s = 0 (lock)
prev = test_and_set( &s->lock, 0 );
if( s->lock == 0 && prev == 1 )
break;
}while(1);
}
void spin_unlock( spinlock* s )
{
test_and_set( &s->lock, 1 ); // unlock
}
// spin lock 획득 가능한가 한번 시도해보고 바로 리턴
int spin_lock_try( spinlock* s )
{
int prev;
prev = test_and_set( &s->lock, 0 );
if( s->lock == 0 && prev == 1 )
return 1; // spin lock 획득!
return 0; // 획득 실패
}
spinlock s;
void task1(void*)
{
spin_lock( &s );
printf("[task1] ok! \n");
Sleep(1000);
printf("[task1] somthing! \n");
spin_unlock( &s );
}
void task2(void*)
{
spin_lock( &s );
printf("[task2] ok! \n");
Sleep(1000);
printf("[task2] somthing! \n");
spin_unlock( &s );
}
int main(int argc, char* argv[])
{
s.lock = 1;
_beginthread( task1, 0, 0 );
_beginthread( task2, 0, 0 );
getch();
return 0;
}
'KB > 기타' 카테고리의 다른 글
MobilePro780 Mips CE2.11 개발툴 (0) | 2006.08.27 |
---|---|
Hidden Markov model (0) | 2006.08.11 |
컴파일러 설계 관련 (0) | 2006.07.19 |
IJG Jpeg 컴파일하기 (VC) (0) | 2006.07.19 |
[펌] 넷피아 한글인터넷도우미 삭제 (0) | 2006.07.10 |