[ÀÌÀü] ¸ñÂ÷ [´ÙÀ½]

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);
}

[ÀÌÀü] ¸ñÂ÷ [´ÙÀ½]