프로그래밍

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
무분별한 사용은 차단될 수 있습니다.
번호 제목 글쓴이 추천 수 날짜 조회 수
5702 [프로그래밍] Aws 람다에 파이썬 올려서 결과 받아오는데 11 아르피쥐 0 1 일 전 221
5701 [프로그래밍] 마리아DB mediumtext 그냥 쓰고 싶은데 21 잉텔 0 1 일 전 172
5700 [프로그래밍] 안드로이드 씹뉴비 질문이요 2 집에가게해줘 0 1 일 전 104
5699 [프로그래밍] c언어 7년했는데 이런게 되는거 처음알았음.. 4 케로로중사 0 3 일 전 674
5698 [프로그래밍] 파이썬 1도 모르는데 GPT로 프로그램 뚝딱 만듬 2 푸르딩딩 1 6 일 전 600
5697 [프로그래밍] 담주 면접잡혔는데 8 삐라루꾸 0 6 일 전 365
5696 [프로그래밍] 아두이노 부트로더를 구웠는데.. 4 렙이말한다ㅡ니가옳다 0 7 일 전 217
5695 [프로그래밍] IOS 개발자 있나여? 1 g4eng 0 9 일 전 238
5694 [프로그래밍] 시스템 디자인 인터뷰 준비 도움좀!!! 1 Nognhyup 0 10 일 전 189
5693 [프로그래밍] 최근에 vscode 쓴 사람 도움! 3 172102 0 11 일 전 439
5692 [프로그래밍] 책을 또 사버리고 말았다... 1 찰나생멸 2 11 일 전 428
5691 [프로그래밍] 윈도우 부팅화면 봐주실분 1 바나나맛두부 0 14 일 전 234
5690 [프로그래밍] 아 시발 퇴사마렵다 9 인간지표 0 15 일 전 592
5689 [프로그래밍] C#이 ㅈ사기 언어인 이유 19 ye 6 15 일 전 1175
5688 [프로그래밍] 요즘 모바일 개발은 어떤 걸 사용하나요? 14 커피좋아용 0 17 일 전 533
5687 [프로그래밍] 취준생 안드로이드 팀플 주제 머할까요... 8 조강현 0 18 일 전 289
5686 [프로그래밍] 공통코드테이블은 대체 왜 만드냐 9 잠적자 0 19 일 전 606
5685 [프로그래밍] 토이프로젝트 주제 선정 3 개드립눈팅1세대 0 19 일 전 283
5684 [프로그래밍] 엥 구글 플러터 유기각 재는거임?? 4 최수연 0 22 일 전 564
5683 [프로그래밍] 반도체 장비 업계인 있음? 9 캡틴띠모 0 22 일 전 431