我有這個簡單的線程創建progrm在C++中,當全局聲明RW鎖時,progrmm按預期方式執行,但是當相同的鎖定聲明是本地(即函數內部)只有一個線程執行,另一個線程掛起。線程掛起在pthread_rwlock_t
工作:
#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);
}
* 非工作: *
#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 2012-08-02 08:11:05
@ user1570478:這是死鎖,因爲您沒有正確初始化鎖,不是因爲有兩個鎖。當你使用未初始化的鎖時,任何事情都可能發生。 – caf 2012-08-02 08:27:11