목적

: pthread 로 멀티 스레드 간의 sync 를 맞추고 timeout 을 주어 자식 thread 가 종료되지 않았을 경우 timeout 전까지 기다린 후 진행한다.


사전 지식

- Process 와 Thread 의 차이

: 프로세스는 운영체제로 부터 주소공간, 메모리, 파일등을 할당 받으며, 리눅스 시스템에서는 코드영역과 라이브러리는 프로세스간 공유하게 된다.

: 스레드란 한 프로세스 내에서 동작되는 흐름으로 하나의 프로세스당 하나의 스레드가 존재하는데 이를 메인스레드라고 부르고, 여러개의 스레드가 하나의 프로세스 내에 있을 경우 멀티 스레드가 된다.


프로세스(Process)

- 자신만의 고유공간(주소공간, 메모리 etc)을 할당 받음

- 다른 프로세스와 의 통신 구현이 쉽지 않음

스레드(Thread) 

- 다른 스레드와 공간과 자원을 공유(시스템 자원 절약)

- 메모리를 공유하기 때문에 전역변수를 활용하여 스레드간 통신이 용이


- Ptread 함수

pthread_mutex_trylock - Lock 시도 시에 다른 스레드에 이미 Lock 이 되어 있을 경우 대기 하지 않고 return 되는 함수

int nRet = pthread_mutex_trylock(&m_mutex);

if (nRet == EBUSY) {

        return true;

} else if (nRet == EINVAL) {

        PMUTEX_TRACE_ERROR("Failed to try lock mutex: %s\n", strerror(nRet));

} else {

        pthread_mutex_unlock(&m_mutex);

}


TEST CODE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
 
// Mutex와 cond 변수
static bool is_finish = false;
pthread_mutex_t sync_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  sync_cond  = PTHREAD_COND_INITIALIZER;
 
// 쓰레드 함수
void *test(void *data)
{
    pthread_mutex_lock(&sync_mutex);
    printf("test++\n");
 
    int i=0;
    int a = *(int *)data;
/*
    while(1){
        printf("%d\n", i++);
        sleep(1);
    };
*/
    for (i = 0; i < 5; i++)
    {
        sleep(1);
        printf("%d\n", i);
    }
 
    printf("test--\n");
    pthread_mutex_unlock(&sync_mutex);
    return (void *)(i * 10);
}
 
int main()
{
    printf("main++\n");
    int a = 100;
    pthread_t thread_t;
    // Cond 를 초기화
    pthread_mutex_init(&sync_mutex, NULL);
    pthread_cond_init(&sync_cond, NULL);
 
    int status;
 
    struct timespec ts;
    int s;
 
    // 쓰레드를 생성한다.
    if (pthread_create(&thread_t, NULL, test, (void *)&a) < 0)
    {
        printf("thread create error:");
        exit(0);
    }
     
    sleep(5);   
 
    printf("trylock++\n");
/*
    while(pthread_mutex_trylock(&sync_mutex) == EBUSY){
        if(retry < 0) break;
        sleep(1);
        printf("Thread is busy, wait for 1s retry =%d\n",retry--);
    }
*/
 
    int retry = 5;
    for(int i =0; i < retry; i++){ // 5초의 기다림.
        int rc = pthread_mutex_trylock(&sync_mutex);
        if(rc == EBUSY) {
            printf("Thread is busy, wait for 1s retry =%d\n", i);
        } else if(rc == 0) {
            printf("Child thread is finished!!\n");
            pthread_mutex_unlock(&sync_mutex);
            break; // 자식 Thread 가 종료되었을 경우, for 문을 나가게 됨.
        } else {
            printf("Unexpected error %d\n", rc);
        }
        sleep(1);
    }
    printf("trylock--\n");   
 
    printf("Thread End %d\n", status);
    return 1;
}


그외 Tip

- pthread 를 gcc 로 compile 하기 위해서는 -lpthread 옵션을 주어야 한다.

: ex - gcc -o test test.cpp -lpthread

- clock_gettime 을 gcc 로 complie 하기 위해서는 -lrt 옵션을 주어야 한다.

설정

트랙백

댓글