线程挂在pthread_rwlock_t中

1 c++ linux pthreads

我在c ++中有一个简单的线程创建程序,在全局声明RW锁时,progrmm按预期执行,但是当将同一锁声明设为本地(即,在函数内部)时,仅一个线程执行,另一个线程挂起。

工作:

#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);

}
Run Code Online (Sandbox Code Playgroud)

*不工作: *

#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);

}
Run Code Online (Sandbox Code Playgroud)

这可能是什么原因?

caf*_*caf 5

在任何一种情况下,您都无法正确初始化mylock变量-在第一种情况下,您只是“幸运”。在全局情况下正确的初始化将是:

pthread_rwlock_t mylock = PTHREAD_RWLOCK_INITIALIZER;
Run Code Online (Sandbox Code Playgroud)

在本地情况下,如果希望线程访问同一锁,则必须声明该锁static

static pthread_rwlock_t mylock = PTHREAD_RWLOCK_INITIALIZER;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,这就是您想要的,因为您要保护对global的访问i。锁应该与数据相关联,因此如果i是全局的,那么对于mylock全局也是有意义的。


如果您真的想要非静态锁(在这种情况下,您不需要),则可以使用:

pthread_rwlock_t mylock;

pthread_rwlock_init(&mylock, NULL);
Run Code Online (Sandbox Code Playgroud)

其次是:

pthread_rwlock_destroy(&mylock);
Run Code Online (Sandbox Code Playgroud)

在函数的末尾。