최근에 시작된 자식 스레드와 마스터 스레드를 동기화하는 데 문제가 있습니다.시작 스레드가 초기화 코드를 실행하기를 기다리는 방법
내가하고 싶은 것입니다 :
- 마스터 스레드가 자식 스레드가 초기화되면
- (시간이 걸릴 수 있습니다) 새 자식 스레드 블록
- 자식 스레드가 시작되고이 초기화를 만들고, 메인 스레드는 계속 (그리고 두 개의 스레드가 병렬로 실행)
내 첫 번째 시도는 같은했다 :
typedef struct threaddata_ {
int running;
} threaddata_t;
void*child_thread(void*arg) {
threaddata_t*x=(threaddata_t)arg;
/* ... INITIALIZE ... */
x->running=1; /* signal that we are running */
/* CHILD THREAD BODY */
return 0;
}
void start_thread(void) {
threaddata_t*x=(threaddata_t*)malloc(sizeof(threaddata_t));
x->running=0;
int result=pthread_create(&threadid, 0, child_thread, &running);
while(!x->running) usleep(100); /* wait till child is initialized */
/* MAIN THREAD BODY */
}
이제 주간 스레드가 필요 이상으로 긴 시간 동안 잠자기 상태가되기 때문에 전혀 마음에 들지 않았습니다. 그래서 나는이 경쟁 조건을 포함, 내가 발견 할 때까지,이 (적절한 신호를 사용하기보다는 내 자신의 대기 루프 롤링) 첫 번째 시도보다 더 제정신 보였다 뮤텍스를 & 조건
typedef struct threaddata_ {
pthread_mutex_t x_mutex;
pthread_cond_t x_cond;
} threaddata_t;
void*child_thread(void*arg) {
threaddata_t*x=(threaddata_t)arg;
/* ... INITIALIZE ... */
pthread_cond_signal(&x->x_cond); /* signal that we are running */
/* CHILD THREAD BODY */
return 0;
}
void start_thread(void) {
threaddata_t*x=(threaddata_t*)malloc(sizeof(threaddata_t));
pthread_mutex_init(&x->x_mutex, 0);
pthread_cond_init (&x->x_cond , 0);
pthread_mutex_lock(&x->x_mutex);
int result=pthread_create(&threadid, 0, child_thread, &running);
if(!result)pthread_cond_wait(&x->x_cond, &x->x_mutex);
pthread_mutex_unlock(&x->x_mutex);
/* MAIN THREAD BODY */
}
를 사용하여 2 차 시도를했다 : 하위 스레드가 초기화를 충분히 빨리 완료하면 (주 스레드가 조건을 대기하기 전에) 기본 스레드가 교착 상태가됩니다.
내 경우는별로 드문 일이 아니므로 정말 쉬운 해결책이 있어야하지만 지금은 볼 수 없습니다.
+1 :'while()'루프에 대해 가짜 웨이크 업 (wake-ups)에 대한 보호를 추가하는데도 사용됩니다. – alk
이것은 OP의 두 가지 접근 방식의 조합 (첫 번째 접근 방식에서'usleep()'이'pthread_cond_wait()'로 대체 됨)와 정확히 같습니다. – caf
첫 번째 접근 방식에서 플래그를 실행하는 것은 뮤텍스에 의해 보호되지 않는다는 점에 유의하십시오. –