프로그래밍

pthread signaling (pthread_cond_signal) 의문점

PThread에서 signaling 하기 전후로 mutex를 넣어서 시그널을 보호하는 다음 구조를 가지는데

예 [1] https://blog.naver.com/PostView.nhn?blogId=leekasong&logNo=221816768753&categoryNo=8&parentCategoryNo=0&viewDate=&currentPage=1&postListTopCurrentPage=1&from=search

예 [2] https://stackoverflow.com/questions/4544234/calling-pthread-cond-signal-without-locking-mutex

 

 

thread 1 producer:
    pthread_mutex_lock(&mutex);

    g_shared_val = 1;                 // setter
    pthread_cond_signal(&cond);  // signal
    pthread_mutex_unlock(&mutex);

 

thread 2 consumer:
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);  // wait signal

    local_val = g_shared_val;                  // getter
    pthread_mutex_unlock(&mutex);

 

 

Q1

thread2가 먼저 구동시

여기서 thread2가 먼저 mutex locking 후 wait에 걸리고

thread1이 그 다음 mutex에 접근하면 mutex로 진입 불가해서

thread1이 무한 대기 걸려야 하는거 아님?

왜 동작이 됨?

 

Q2

thread1이 먼저 구동시

pthread_cond_wait이 없는데, pthread_cond_signal 신호가 왜 thread2 다음 구동 시에 pthread_cond_wait이 풀림??

mutex locking으로 인해서 thread2는 pthread_cond_wait에 도달하지 못 한 상태인데??

pthread_cond_wait 중인 쓰레드가 있어야지 pthread_cond_signal로 wakeup이 되는거 아님?

그리고 pthread_cond_wait 중인 쓰레드가 없으면 pthread_cond_signal은 무시되는거 아님?

 

* 판단 미스인듯 정상 무시되는 것으로 보임

 

 

 

 

 

 

`````````````````````````````````````````````````

풀 소스

`````````````````````````````````````````````````

 

 

 

/* inc */

#include <stdio.h>

#include <stdint.h>

#include <pthread.h>

#ifdef __linux__

#include <unistd.h>  // POSIX sleep

#define msleep(time) usleep(time * 1000)  // linux nanoseconds timer

#endif  // __linux__

#if (defined(_WIN32) || defined(_WIN64))

#include <windows.h> // Win32 Win32

#define msleep(time) Sleep(time)          // win32 milliseconds timer

#endif // _WIN32, _WIN64

 

/* shared memory */

int32_t          g_flag_run = 1;

int32_t          g_val = 0;

pthread_cond_t   g_cond;

pthread_mutex_t  g_mutex;

 

/* thread entry function */

void* thread_producer(void *p_entry_arg) {

 

    // stack

    int32_t thread_id = *((int32_t*)p_entry_arg);

    int32_t loop = 0;

    int32_t iret;

 

    // loop

    msleep(100);    // sleep

    printf("[Producer #%d] thread is started\n", thread_id);

    while (g_flag_run) {

        iret = pthread_mutex_lock(&g_mutex);

        if (iret != 0) {

            printf("[Producer #%d] locking is failed\n", thread_id);

        }

        ++g_val;

        pthread_cond_signal(&g_cond);

        pthread_mutex_unlock(&g_mutex);

        printf("[Producer #%d] send %d\n", thread_id, g_val);

 

        msleep(200);    // sleep

        ++loop;

    }

    printf("[Producer #%d] thread is reached the end point\n", thread_id);

    return NULL;

}

 

/* thread entry function */

void* thread_consumer(void *p_entry_arg) {

 

    // stack

    int32_t thread_id = *((int32_t*)p_entry_arg);

    int32_t loop = 0;

    int32_t iret;

    int32_t local_val = 0;

 

    // loop

    printf("[Consumer #%d] thread is started\n", thread_id);

    while (g_flag_run) {

 

        iret = pthread_mutex_lock(&g_mutex);

        if (iret != 0) {

            printf("[Consumer #%d] locking is failed\n", thread_id);

            continue;

        }

        if (1) {

            pthread_cond_wait(&g_cond, &g_mutex);

            local_val = g_val;

            printf("[Consumer #%d]          got %d\n", thread_id, local_val);

        }

        pthread_mutex_unlock(&g_mutex);

 

        msleep(1);  // sleep

        ++loop;

    }

    printf("[Consumer #%d] thread is reached the end point\n", thread_id);

    return NULL;

}

 

/* main thread */

void run(void) {

 

    // stack

    uint32_t uret;

    int32_t iret;

 

    /* thread */

    pthread_t thread[2];

    int32_t   arg[2] = {0, 1};

 

    /* creator */

    iret = pthread_cond_init(&g_cond, NULL);

    if (iret != 0) {

        printf("pthread_cond_init is failed (%d)\n", iret);

    }

    iret = pthread_mutex_init(&g_mutex, NULL);

    if (iret != 0) {

        printf("pthread_mutex_init is failed (%d)\n", iret);

    }

    iret = pthread_create(&thread[0], NULL, thread_producer, &(arg[0]));

    if (iret != 0) {

        printf("pthread_create is failed (%d)\n", iret);

    }

    iret = pthread_create(&thread[1], NULL, thread_consumer, &(arg[1]));

    if (iret != 0) {

        printf("pthread_create is failed (%d)\n", iret);

    }

 

    // ctrl func

    printf("[Main thread] msleep is started\n");

    msleep(5 * 1000);

    printf("[Main thread] Sleep is done\n");

 

    // destroyer

    printf("[Main thread] Destroyer is started (with 2sec sleeping)\n");

    g_flag_run = 0;

    msleep(2000);

    for (int32_t i = 0; i < 2; i++) {

        pthread_cancel(thread[i]);

        iret = pthread_detach(thread[i]);

        if (iret != 0) {

            printf("[Main thread] pthread_detach is failed (%d)\n", iret);

        }

    }

    pthread_mutex_destroy(&g_mutex);

    pthread_cond_destroy(&g_cond);

    printf("[Main thread] Destroyer is done\n");

}

 

/* main */

int32_t main(void) {

    run();

    return 0;

} // main()

 

````````````````````````````````````````````````

4개의 댓글

2024.03.02

"These functions atomically release mutex and cause the calling thread to block on the condition variable cond"

"Upon successful return, the mutex is locked and owned by the calling thread."

- https://www.ibm.com/docs/en/aix/7.3?topic=p-pthread-cond-wait-pthread-cond-timedwait-subroutine

 

pthread_cond_wait 때문에 consumer 스레드에서 mutex 해제됨 => producer 진행 => cond 설정 => consumer 돌아감 => 반복

1
2024.03.02
@OpenGL47

정말 감사합니다.

브레이킹 같이 찍어보면; consumer mutex락 => consumer cond wait 도달 => consumer mutex 강제 해제 => producer mutex 락 => producer cond => producer mutex 언락 => consumer 돌아감 (스케쥴링이 알아서) => consumer mutex 락 => consumer cond wait 리턴 => consumer mutex 언락 => 반복

이 순서인 것 같네요

뭔 순서가 ㅋㅋㅋㅋㅋ 감사합니다. 거참 동작이 어렵게 되어 있네요. 다음부터는 IBM AIX 문서 잘 참고하도록 하겠습니다.

1
2024.03.02
@OpenGL47
0
2024.03.02
@아리
0
무분별한 사용은 차단될 수 있습니다.
번호 제목 글쓴이 추천 수 날짜 조회 수
180653 [모바일] 아이폰16 VS SE4 + 워치 2 누군가는해야하잖아 0 28 분 전 37
180652 [컴퓨터] 형님들 급함!! 기존 HDD사용중 SDD추가 할려는데 윈도우 1 아응에 0 29 분 전 23
180651 [컴퓨터] 와이파이에서 직결로 바꾸니 빠르네 즈기 0 31 분 전 35
180650 [컴퓨터] 모니터가 눈이 아픈데 조정가능함?? 정글은언제나맑음... 0 35 분 전 7
180649 [모바일] 혹시 화면크기 조정하는 법이나 이거 해결하는 법 아는 똑똑... 2 트레센카페트 0 55 분 전 15
180648 [컴퓨터] 다른거 그대로 유지하면서 파워랑 글카만 바꾸는거 안어렵겠지? 3 너가전부옳아 0 1 시간 전 26
180647 [모바일] 버즈2 프로 한쪽 사기 vs 그냥 신제품 사기 4 김승상네국밥 0 1 시간 전 50
180646 [모바일] 휴대폰 보조배터리 추천부탁드림니다 2 아이뽕 0 2 시간 전 26
180645 [견적] 이륙허가2최종.txt 1 뚜루뚜뚜뚜 0 2 시간 전 36
180644 [컴퓨터] 노트북 이륙 ㄱㅊ? 김치치가 0 2 시간 전 32
180643 [컴퓨터] 로아 하면서 유튜브만 재생하면 프레임 떨어짐 3 네임드 0 3 시간 전 83
180642 [견적] 이거 싼거임? 6 유출 0 3 시간 전 61
180641 [프로그래밍] 아 시발 퇴사마렵다 7 인간지표 0 4 시간 전 205
180640 [컴퓨터] 커세어 K65 RGB PLUS 후기 2 커뮤니티 0 12 시간 전 249
180639 [프로그래밍] C#이 ㅈ사기 언어인 이유 17 ye 4 13 시간 전 689
180638 [모바일] Poke5 2024년형 고민되네 8 PremiumAir 0 14 시간 전 133
180637 [잡담] 하 시발.. 한무무 풀윤활 다했는데 ye 0 14 시간 전 148
180636 [잡담] 스팀 클라이언트 실행이 안되는데 고치는법 아는사람? 2 hideonbush 0 15 시간 전 63
180635 [잡담] 길거리 전단지 인터넷 가입 광고보고 가입해두뎀? 4 내일까지 0 15 시간 전 91
180634 [모바일] 아이패드프로11 키보드케이스 추천좀 2 cw 7 0 15 시간 전 41