죄송합니다.이 코드는 여기에 있습니다. http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html이 뮤텍스는이 코드로 설명되었지만 약간 이상했습니다. 나는 뮤텍스의 기능을 이해하고 그것의 임계 영역에서 공유 변수를 보호한다. 여기의 구체적인 것은 나를 혼란스럽게하고있다! 필자는 필자가 pthread_create를 사용하여 새 스레드를 만들고 카운터를 증가시키는 functionC 프로세스를 실행 중입니다. 카운터는 보호 된 변수이며 두 함수가 동시에 실행 중이므로 뮤텍스에 의해 보호되지 않은 경우 카운터는 잘못된 값을 반환합니다.몇 가지 간단한 C 코드 내가 이해할 수 없다 - 여기서 뮤텍스는 무엇입니까?
이 정보가 올 바르고 올바른가요? 고마워. :).
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{
int rc1, rc2;
pthread_t thread1, thread2;
/* Create independent threads each of which will execute functionC */
if((rc1=pthread_create(&thread1, NULL, &functionC, NULL)))
{
printf("Thread creation failed: %d\n", rc1);
}
if((rc2=pthread_create(&thread2, NULL, &functionC, NULL)))
{
printf("Thread creation failed: %d\n", rc2);
}
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
exit(0);
}
void *functionC()
{
pthread_mutex_lock(&mutex1);
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock(&mutex1);
}
이것은 하나의 가능한 시나리오이지만 다른 하나는 '카운터'의 최종 값은 예상되는 2가 아닌 1입니다. "카운터 값 : 1"이 두 번 표시되면 결국 나타날 수 있습니다. –
참. C 언어는 ++ 연산이 원 자성인지 여부를 정의하지 않습니다. –