|
[이전]
목차
[다음]
Simple DirectMedia Layer API 사용하기
쓰레드(Threads)
SDL_CreateThread() 에 여러분의 함수를 넘겨줌으로써 쓰레드를 만들 수 있다.
SDL_CreateThread()가 성공적으로 리턴된다면, 여러분의 함수는 이제 애플리케이션의
나머지 부분동안에 동시에 수행된다. 자신의 실행 컨텍스트(스택,
레지스터, 등등)를 가지며, 애플리케이션의 나머지 부분에 의해 사용되는
메모리와 파일 핸들을 액세스할 수도 있다.
|
팁:
SDL_CreateThread() 의 두번째 인수는 쓰레드 함수에 대한 인수로 넘겨진다.
이 인수를 통해 스택상에 데이타 자체를 넘겨줄 수도 있고, 쓰레드에 의해
사용될 데이타에 대한 포인터로 사용할 수도 있다.
|
예제:
#include "SDL_thread.h"
int global_data = 0;
int thread_func(void *unused)
{
int last_value = 0;
while ( global_data != -1 ) {
if ( global_data != last_value ) {
printf("Data value changed to %d\n", global_data);
last_value = global_data;
}
SDL_Delay(100);
}
printf("Thread quitting\n");
return(0);
}
{
SDL_Thread *thread;
int i;
thread = SDL_CreateThread(thread_func, NULL);
if ( thread == NULL ) {
fprintf(stderr, "Unable to create thread: %s\n", SDL_GetError());
return;
}
for ( i=0; i<5; ++i ) {
printf("Changing value to %d\n", i);
global_data = i;
SDL_Delay(1000);
}
printf("Signaling thread to quit\n");
global_data = -1;
SDL_WaitThread(thread, NULL);
}
|
뮤텍스(mutex)를 생성하고 잠금(SDL_mutexP())과 해제(SDL_mutexV())를
통해 하나 이상의 쓰레드가 하나의 리소스를 액세스하는 제한할 수 있다.
|
팁:
하나이상의 쓰레드에 의해 액세스할 수있는 모든 데이타는 뮤텍스(mutex)에
의해 보호되어져야 한다.
|
예제:
#include "SDL_thread.h"
#include "SDL_mutex.h"
int potty = 0;
int gotta_go;
int thread_func(void *data)
{
SDL_mutex *lock = (SDL_mutex *)data;
int times_went;
times_went = 0;
while ( gotta_go ) {
SDL_mutexP(lock); /* potty 를 잠근다 */
++potty;
printf("Thread %d using the potty\n", SDL_ThreadID());
if ( potty > 1 ) {
printf("Uh oh, somebody else is using the potty!\n");
}
--potty;
SDL_mutexV(lock);
++times_went;
}
printf("Yep\n");
return(times_went);
}
{
const int progeny = 5;
SDL_Thread *kids[progeny];
SDL_mutex *lock;
int i, lots;
/* 동기화를 위한 lock 생성 */
lock = SDL_CreateMutex();
gotta_go = 1;
for ( i=0; i<progeny; ++i ) {
kids[i] = SDL_CreateThread(thread_func, lock);
}
SDL_Delay(5*1000);
SDL_mutexP(lock);
printf("Everybody done?\n");
gotta_go = 0;
SDL_mutexV(lock);
for ( i=0; i<progeny; ++i ) {
SDL_WaitThread(kids[i], &lots);
printf("Thread %d used the potty %d times\n", i+1, lots);
}
SDL_DestroyMutex(lock);
}
|
[이전]
목차
[다음]
|