RW 잠금이 전역 적으로 선언되고 progrmm이 예상대로 실행되는 동안 C++에서이 간단한 스레드 생성 progrm을 가졌지 만 동일한 잠금 선언이 로컬 (즉, 함수 내부)으로 만들어지면 하나의 스레드 다른 스레드가 중단됩니다.스레드가 pthread_rwlock_t에 있습니다.
WORKING :
#include <iostream>
#include <pthread.h>
using namespace std;
int i = 0;
**pthread_rwlock_t mylock;** //GLOBAL
void* IncrementCounter(void *dummy)
{
cout << "Thread ID " << pthread_self() << endl;
int cnt = 1;
while (cnt < 50)
{
pthread_rwlock_wrlock(&mylock);
++i;
pthread_rwlock_unlock(&mylock);
++cnt;
cout << "Thread ID (" << pthread_self() << ") Incremented Value : " << i << endl;
}
}
int main()
{
pthread_t thread1,thread2;
int ret, ret1;
ret = pthread_create(&thread1,NULL,IncrementCounter,NULL);
ret1 = pthread_create(&thread2,NULL,IncrementCounter,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
}
* NON WORKING : 이것에 대한 *
#include <iostream>
#include <pthread.h>
using namespace std;
int i = 0;
void* IncrementCounter(void *dummy)
{
cout << "Thread ID " << pthread_self() << endl;
int cnt = 1;
**pthread_rwlock_t mylock;** //LOCAL
while (cnt < 50)
{
pthread_rwlock_wrlock(&mylock);
++i;
pthread_rwlock_unlock(&mylock);
++cnt;
cout << "Thread ID (" << pthread_self() << ") Incremented Value : " << i << endl;
}
}
int main()
{
pthread_t thread1,thread2;
int ret, ret1;
ret = pthread_create(&thread1,NULL,IncrementCounter,NULL);
ret1 = pthread_create(&thread2,NULL,IncrementCounter,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
}
무엇을 할 수있는 가능한 이유?
설명해 주셔서 감사합니다. 나는 전역 변수에 대해 두 개의 잠금을 가짐에있어 아무런 포인트가 없다는 것을 알고있다. 그러나 두 개의 잠금이있는 경우 두 가지 잠금이 서로 다른 잠금이되므로 잠금이 풀리면 다른 잠금이 해제됩니다. 왜 교착 상태입니까? 하나의 글로벌 변수를 2 개의 다른 잠금으로 잠그지 않아야합니까? 정교하게 주시겠습니까? – user1570478
@ user1570478 : 잠금 장치가 제대로 초기화되지 않았기 때문에 교착 상태입니다. 두 개의 잠금이 있기 때문에가 아닙니다. 초기화되지 않은 잠금을 사용하면 아무 일도 일어나지 않을 수 있습니다. – caf