- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在 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/
我如何才能看到(在 linux 上)哪些线程拥有 pthread_rwlock_t(或 std::shared_mutex)? 对于常规互斥锁,有 Is it possible to determin
我正在声明 pthread_rwlock_t 静态全局数组。例如静态 pthread_rwlock_t cm[255];在构造函数内部,我想初始化 255 个互斥量之一(我用静态计数器跟踪) 现在我很
pthread_rwlock t1; pthread_rwlock_wrlock(&t1); pthread_rwlock t2 = t1; 发生了什么事?t2 是否锁定? 最佳答案 没有什么特别的事
有人可以总结一下 pthread_rwlock_t 的不同成员的含义吗? struct { int __lock; unsigned int __nr_readers; u
我在 C++ 中有这个简单的线程创建程序,在全局声明 RW 锁期间,progrmm 按预期执行,但是当在本地(即函数内部)声明相同的锁时,只有一个线程执行,另一个线程挂起。 工作: #include
robustness互斥量对我的程序非常重要,因为它可以处理进程在不释放互斥量的情况下死亡的情况。 但是根据文档,pthread_mutexattr_setrobust只适用于pthread_mute
我在 linux 上工作,我正在使用 pthread_rwlock,它存储在共享内存中并在多个进程之间共享。这大部分工作正常,但是当我杀死一个持有锁的进程 (SIGKILL) 时,看起来锁仍然持有(无
我是一名优秀的程序员,十分优秀!