我有这个简单的线程创建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