뮤텍스와 두 개의 스레드를 동기화 할 때 도움이 필요합니다. Iam C와 뮤텍스를 처음 접했고 여기서 무엇을해야할지 모르겠다. 이 코드에는 10 개로 계산되고 각 숫자가 인쇄되지만 동기화되지 않는 두 개의 스레드가 있으므로 동기화되지 않고 절반 동기화됩니다. 나가 말썽을 단지 끝에 얻는 것을 의미한다, 때때로 8 .. 9 .. 11, 8 .. 9 .. 10 .. 10 등등을 인쇄한다.C에서 뮤텍스를 사용하여 두 개의 pthread 동기화하기
뮤텍스에 대한 라인을 없애면 원시 코드를 변경할 수 없습니다. 즉, 원시 코드입니다. 뮤텍스에 대해서만 줄을 추가 할 수 있습니다.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_mutex_t mutex;
int g_ant = 0;
void *writeloop(void *arg) {
while(g_ant < 10) {
pthread_mutex_lock(&mutex);
g_ant++;
usleep(rand()%10);
printf("%d\n", g_ant);
pthread_mutex_unlock(&mutex);
}
exit(0);
}
int main(void)
{
pthread_t tid;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid, NULL, writeloop, NULL);
writeloop(NULL);
pthread_join(tid, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
가 코드 – 75inchpianist
'정의되지 않은 참조를 모두 게시하시기 바랍니다 '지금 – zch
죄송합니다, 고정 코드를 writeloop''. 다시 시도하십시오 :) – Codebox