PThread에서 signaling 하기 전후로 mutex를 넣어서 시그널을 보호하는 다음 구조를 가지는데
예 [1] https://blog.naver.com/PostView.nhn?blogId=leekasong&logNo=221816768753&categoryNo=8&parentCategoryNo=0&viewDate=¤tPage=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()
````````````````````````````````````````````````
OpenGL47
"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 돌아감 => 반복
아리
정말 감사합니다.
브레이킹 같이 찍어보면; consumer mutex락 => consumer cond wait 도달 => consumer mutex 강제 해제 => producer mutex 락 => producer cond => producer mutex 언락 => consumer 돌아감 (스케쥴링이 알아서) => consumer mutex 락 => consumer cond wait 리턴 => consumer mutex 언락 => 반복
이 순서인 것 같네요
뭔 순서가 ㅋㅋㅋㅋㅋ 감사합니다. 거참 동작이 어렵게 되어 있네요. 다음부터는 IBM AIX 문서 잘 참고하도록 하겠습니다.
아리
OpenGL47