gpt4 book ai didi

c++ - 线程在 pthread_rwlock_t 中挂起

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:36 24 4
gpt4 key购买 nike

我在 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);

}

*不工作:*

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

}

这可能是什么原因?

最佳答案

在这两种情况下,您都没有正确初始化 mylock 变量 - 在第一种情况下,您只是获得了“幸运”。在全局情况下正确的初始化是:

pthread_rwlock_t mylock = PTHREAD_RWLOCK_INITIALIZER;

在本地情况下,如果您希望您的线程访问相同 锁,则必须将其声明为static:

static pthread_rwlock_t mylock = PTHREAD_RWLOCK_INITIALIZER;

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


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

pthread_rwlock_t mylock;

pthread_rwlock_init(&mylock, NULL);

其次是:

pthread_rwlock_destroy(&mylock);

在函数的末尾。

关于c++ - 线程在 pthread_rwlock_t 中挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11772176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com