프로그래밍

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
무분별한 사용은 차단될 수 있습니다.
번호 제목 글쓴이 추천 수 날짜 조회 수
5689 [프로그래밍] 엥 구글 플러터 유기각 재는거임?? 4 최수연 0 15 시간 전 183
5688 [프로그래밍] 반도체 장비 업계인 있음? 9 캡틴띠모 0 1 일 전 208
5687 [프로그래밍] 안드로이드 책 추천좀 6 집에가게해줘 0 2 일 전 126
5686 [프로그래밍] 폰 스크리닝 해 본 사람 있어? 3 무지개빛푸딩 0 2 일 전 357
5685 [프로그래밍] jsp 트리메뉴 만들고있는데 구상한게가능한지 의견좀물어볼께 11 평택국 0 3 일 전 142
5684 [프로그래밍] JPA 도와줘어억 ㅠ 10 모그리또 0 3 일 전 222
5683 [프로그래밍] 의사는 뽑는 인원 제한하는데 부캠은 왜 제한 안 할까 5 조강현 0 5 일 전 350
5682 [프로그래밍] 그 혹시 게임쪽 종사자 있음? 17 god79ii 0 9 일 전 616
5681 [프로그래밍] 코린이 ㅅㅂ 뭐가 문젠지 모르겠어요 9 집에가게해줘 0 9 일 전 436
5680 [프로그래밍] Dear Imgui 라고 아시나요? 2 년째모쏠 0 9 일 전 239
5679 [프로그래밍] 현업개발자분들 주말엔 편하게 쉴수있나요? 10 키로 0 10 일 전 841
5678 [프로그래밍] 무엇이든 물어보세요. 28 변현제 0 12 일 전 404
5677 [프로그래밍] 개발자보단 엔지니어가 취업이 잘됨 5 iillillill 2 13 일 전 713
5676 [프로그래밍] 프론트엔드 개발자 연봉 1억 넘는 사람 있어? 13 잠적자 0 13 일 전 622
5675 [프로그래밍] Exiftool 이거 일본어 못 읽는데 13 부터시작하는이세... 0 15 일 전 231
5674 [프로그래밍] 반응형 웹페이지가 내가상상한거랑 좀 다르네 4 평택국 0 16 일 전 442
5673 [프로그래밍] 고졸 FE개발자 연봉, 상황에 조언좀.. 19 쾅꿍꿍 0 16 일 전 596
5672 [프로그래밍] 물경력들 보면 책임을 이해못하는것같음 5 mils 1 17 일 전 407
5671 [프로그래밍] GPT가 코딩 다해주네 3 겜신병자 0 17 일 전 739
5670 [프로그래밍] 크로스플랫폼의 욕심은 끝이없다 4 ye 0 20 일 전 397