2017-12-21 6 views
1

구조체에 저장된 카운터의 값을 증가시키고 싶습니다. 3 개의 스레드가 사람들의 수를 늘리기 위해 tattoo_shop이라는 글꼴로 들어 오지만 몇 가지 이유로 number_of_people의 값은 동일하게 유지됩니다.C에서 다중 스레드 구조 값을 증가시키는 방법

순차적으로 사례를 재현하려고 시도했는데 작동 중입니다. 쓰레드로 작업 할 때 뭔가 특별한 것이 있습니까? 당신에게 :) 감사

typedef struct { 
    int number_of_people; 
}Queue; 

void *tattoo_shop(void *arguments){ 
    Client *args = arguments; 
    Queue the_queue; 

    add_to_the_queue(&the_queue,args); 
} 

void add_to_the_queue(Queue *the_queue, Client *the_client) { 

    pthread_mutex_lock(&mutex_queue); 
    the_queue->number_of_people++; 
    pthread_mutex_unlock(&mutex_queue); 

    printf("The thread %d is changing the counter of the queue which is now %d \n",the_client->id,the_queue->number_of_people); 
} 

출력 : Queue the_queue;는 지역 변수가 아닌 공유 한 이후

The thread 1 is changing the counter of the queue which is now 1 
The thread 0 is changing the counter of the queue which is now 1 
The thread 2 is changing the counter of the queue which is now 1 
+1

the_queue는 지역 변수이며, 당신이 루틴을 호출 할 때마다, 그것은 – Ora

+0

새롭게 그것은 당신의 여러 스레드가 같은 큐를 공유 결국 어떻게 나에게 분명하지 않다 intialized 것 : 약간의 조정은이 문제를 해결합니다. –

+0

@OliverCharlesworth 내 스레드는 모두 tattoo_shop 함수에 있으며 그 함수에서 add_to_the_queue 함수를 사용합니다. – MaxUt

답변

2

귀하의 코드가 넌센스입니다.

그러나 파일 범위에 할당되었거나 static으로 코드가 대부분 괜찮습니다. 다른 곳에서 객체에 대한 쓰기가 원자적일 수 있다는 보장이 없으므로, 침입자가 뮤텍스 가드 외부의 공유 객체를 읽지 않아야합니다.

{ 
    pthread_mutex_lock(&mutex_queue); 
    int people = the_queue->number_of_people++; 
    pthread_mutex_unlock(&mutex_queue); 

    printf("%d", people); 
} 
+0

the_queue를 어떻게 공유 할 수 있습니까? 문제는 tattoo_shop에서 테스트를 수행하기 위해 add_to_the_queue 함수에서이 데이터를 가져와야한다는 것입니다. – MaxUt

+0

@MaxUt : 함수 외부의 대기열을 정의합니다 (파일 정적 변수). 또한 0으로 초기화됩니다. 코드가 초기화되지 않은 변수를 증가 시키면 메모리가 제로화되는 것은 운이 좋을 것입니다 (이전 프로세스가 동일한 실제 메모리에 저장되어 있지만 표준에 의해 보장되지 않는 데이터를 보지 못하도록하기 위함). 그리고 대기열에 대한 모든 액세스는 뮤텍스에 의해 조정되어야합니다 (이 코드는 표시된 코드에서 정의되거나 선언되지 않지만 파일 범위 변수 여야 함). 인쇄 코드는 뮤텍스 잠금/잠금 해제 쌍의 범위 내에 있어야합니다. –

관련 문제