[英]c++ double shared_lock freezes the program on windows
When I am learning shared_mutex
in C++17, I find a weired problem.当我在 C++17 中学习
shared_mutex
时,我发现了一个奇怪的问题。 If I call shared_lock
twice in one thread, and call unique_lock
in another thread, then my program will freeze.如果我在一个线程中调用
shared_lock
两次,并在另一个线程中调用unique_lock
,那么我的程序将冻结。 Like this:像这样:
std::mutex mutex;
std::shared_mutex s_mutex;
int i = 0;
void func() {
auto lock = std::shared_lock(s_mutex);
auto lock1 = std::shared_lock(s_mutex);
++i;
}
void func2() {
auto lock = std::unique_lock(s_mutex);
++i;
}
int main() {
auto t1 = std::thread([](){
auto i = 10000;
while(i--) {
func();
}
});
auto t2 = std::thread([](){
auto i = 10000;
while(i--) {
func2();
}
});
t2.join();
t1.join();
std::cout << i << std::endl;
return 0;
}
This problem seems only appear on windows, I tried it on Arch linux, it works well.这个问题好像只出现在windows上,我在Arch linux上试过,效果很好。
I'm using g++.exe (Rev2, Built by MSYS2 project) 12.1.0
.我正在使用
g++.exe (Rev2, Built by MSYS2 project) 12.1.0
。
I tried add cout
after every lock like:我尝试在每次锁定后添加
cout
,例如:
void func() {
auto lock = std::shared_lock(s_mutex);
std::cout << "t1 lock1\n";
auto lock1 = std::shared_lock(s_mutex);
std::cout << "t1 lock2\n";
++i;
}
Then I find it always freezes after t1 lock1\n
, so I tried to step into lock1's constructor, and I find it freeze after this function:然后我发现它总是在
t1 lock1\n
之后冻结,所以我尝试进入 lock1 的构造函数,我发现它在这个 function 之后冻结:
static inline int
__gthread_active_p (void)
{
return 1;
}
But I don't know why.但我不知道为什么。 Thanks in advance.
提前致谢。
Trying to lock the mutex again in a thread that already holds a lock on the mutex has undefined behavior.尝试在已经持有互斥锁的线程中再次锁定互斥锁具有未定义的行为。
This applies to all mutex types except the recursive*
ones.这适用于除
recursive*
之外的所有互斥锁类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.