我在 C++ 中有这个简单的线程创建程序,在全局声明 RW 锁期间,程序按预期执行,但是当在本地(即在函数内部)进行相同的锁声明时,只有一个线程执行,另一个线程挂起。
在职的:
#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);
}
这可能是什么原因?