pthread 예제 코드

프로그래밍/c,c++ 2022. 5. 9. 22:37
반응형

pthread 사용을 위한 기본 예제

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

static bool sIsStop = false;
static pthread_t sThreadId = 0;

static void *testThread(void *data) {
    while (true) {
        if (sIsStop) {
            break;
        }

        printf("%s[%d] TID = %d Running thread\n", __FUNCTION__, __LINE__, gettid());
        // add code

        usleep(1000 *1000);
    }

    sThreadId = 0;

    return NULL;
}

int startThread() {
    if (sThreadId == 0) {
        sIsStop = false;
        pthread_create(&sThreadId, NULL, &testThread, NULL);
    }
    else {
        printf("%s[%d] Thread is running\n", __FUNCTION__, __LINE__);
    }

    return 0;
}

int stopThread() {
    if (sThreadId != 0) {
        sIsStop = true;
        pthread_join(sThreadId, NULL);
    }
    else {
        printf("%s[%d] Thread is not running\n", __FUNCTION__, __LINE__);
    }
    return 0;
}

int main() {
    startThread();

    usleep(1000 *1000);
    printf("%s[%d] TID = %d test print\n", __FUNCTION__, __LINE__, gettid());
    usleep(1000 *1000);
    printf("%s[%d] TID = %d test print\n", __FUNCTION__, __LINE__, gettid());
    usleep(1000 *1000);
    printf("%s[%d] TID = %d test print\n", __FUNCTION__, __LINE__, gettid());

    stopThread();

    return 0;
}

 

실행 결과

$ ./a.out               
testThread[14] TID = 23131 Running thread
main[52] TID = 23130 test print
testThread[14] TID = 23131 Running thread
main[54] TID = 23130 test print
testThread[14] TID = 23131 Running thread
main[56] TID = 23130 test print
testThread[14] TID = 23131 Running thread
반응형
: