ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • pthread_mutex_init (뮤텍스 사용하기!)
    C_C++ 프로그래밍 2019. 5. 25. 01:59


    개발 환경

     OS

     Ubuntu 18.04.2

     컴파일러

     gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04)




    int pthread_mutex_init(pthread_mutex_t * mutex,
    const pthread_mutex_attr *attr);


    mutex 객체를 초기화 시킨다.
    attr은 특성인데, 기본적인 뮤텍스를 원한다면 NULL로 설정하면 된다.

    critical section = 임계 구역 (하나의 쓰레드만 접근이 가능)




    pthread_mutex_t

    구조체


    pthread_mutex_lock();

    lock을 걸어 임계 구역을 시작한다.


    pthread_mutex_unlock();

    lock을 풀어 임계 구역을 해제한다.



    소스코드


    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
    #include<stdio.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<unistd.h>
     
    // init mutex container
    pthread_mutex_t mutex_lock;
     
    // share resource
    int share = 0;
     
    void *thread_function(void *data){
            int i;
            char *thread_name = (char *) data;
     
    // lock
            pthread_mutex_lock(&mutex_lock);
     
            // critical section start
            share = 0;
            for(i = 0; i < 3; i++){
                    printf("%s Count : %d\n", thread_name, share);
                    share++;
                    sleep(2);
            }
            // critical section end
    // mutex unlock
            pthread_mutex_unlock(&mutex_lock);
    }
     
    int main(){
            pthread_t p_thread1, p_thread2;
            int status;
     
            // mutex container init
            pthread_mutex_init(&mutex_lock, NULL);
            pthread_create(&p_thread1, NULL, thread_function, (void *"THREAD 1");
            pthread_create(&p_thread2, NULL, thread_function, (void *"THREAD 2");
     
            pthread_join(p_thread1, (void *)&status);
            pthread_join(p_thread2, (void *)&status);
            return 0;
    }
     
    cs





    실행결과

    mutex가 없는 경우

    1
    2
    3
    4
    5
    6
    THREAD 1 Count : 0
    THREAD 2 Count : 0
    THREAD 1 Count : 2
    THREAD 2 Count : 3
    THREAD 2 Count : 4
    THREAD 1 Count : 4
    cs



    mutex를 사용한 경우

    1
    2
    3
    4
    5
    6
    7
    THREAD 1 Count : 0
    THREAD 1 Count : 1
    THREAD 1 Count : 2
    THREAD 2 Count : 0
    THREAD 2 Count : 1
    THREAD 2 Count : 2
     
    cs




    ※ 본 글은 개인 포트폴리오 혹은 공부용으로 사용하기 때문에, 무단 복사 유포는 금지하지만, 개인 공부 용도로는 얼마든지 사용하셔도 좋습니다




    반응형
Designed by Tistory.