为什么此 C++ 多线程互斥代码偶尔会出现故障?



我在Linux Debian系统上使用以下foo.cpp代码:

#include <iostream>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <thread>
std::mutex mtx;
std::condition_variable cvar;
long next = 0;
void doit(long index){
std::unique_lock<std::mutex> lock(mtx);
cvar.wait(lock, [=]{return index == next;});
std::cout<< index << std::endl;
++next;
mtx.unlock();
cvar.notify_all();
return;
}
int main() 
{
long n=50;
for (long i=0; i < n; ++i)
std::thread (doit,i).detach();
while(next != n)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return(0);
}

我编译它:

g++ -std=c++14 -pthread -o foo foo.cpp

它被设计为触发 50 个线程,分离,这些线程由互斥锁控制,并在函数 doit 中condition_variable,因此它们按顺序执行互斥块。

它大部分时间都在工作,将数字 00 到 49 写入屏幕,然后终止。

但是,它有两种偶尔的故障模式:

故障模式 1:上升到某个任意数字<50 后,它会中止并显示错误:

福: ../nptl/pthread_mutex_lock.c:80: __pthread_mutex_lock:断言"mutex->__data.__owner == 0"失败。

故障模式 2:上升到某个任意数字<50 后,它挂起,必须使用 ctrl-C 杀死才能返回到终端提示符。

我将不胜感激有关此行为的原因以及如何解决它的任何建议。

====

==================================================================================编辑:好的,所以这是一个工作修订版本。我修复了这两个错误,并将锁名称从"lock"更改为"lk"以减少混淆。感谢您的帮助。

#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
std::mutex mtx;
std::condition_variable cvar;
long next = 0;
void doit(long index){
std::unique_lock<std::mutex> lk(mtx);
cvar.wait(lk, [=]{return index == next;});
std::cout<< index << std::endl;
++next;
lk.unlock();
cvar.notify_all();
return;
}
int main()
{
long n=50;
for (long i=0; i < n; ++i)
std::thread (doit,i).detach();
{
std::unique_lock<std::mutex> lk(mtx);
cvar.wait(lk, [=]{return n == next;});
}
return(0);
}

>while(next != n)尝试访问变量next,这些变量可以通过工作线程进行修改,而无需任何同步创建争用条件。它应该由相同的互斥锁覆盖:

{
std::unique_lock<std::mutex> lock(mtx);
cvar.wait(lock, [=]{return n == next;});
}

分离线程不是一个好主意。您应该将它们存放在某个地方,然后在从main返回之前join

更新:您正在尝试在mutex本身上调用unlock,而不是在锁定对象上调用它。通过构造锁定对象,您将解锁互斥锁的责任委托给lock对象。它应该是

lock.unlock();
cvar.notify_all();

我不重新命令分离线程,因为在那之后您无法加入它们。 如果你真的想这样做,那么使用条件变量来同步下一个数据。

void doit(long index){
std::unique_lock<std::mutex> lock(mtx);
cvar.wait(lock, [=]{return index == next;});
std::cout<< index << std::endl;
++next;
cvar.notify_all();
return;
}
int main() 
{
long n=50;
for (long i=0; i < n; ++i)
std::thread (doit,i).detach();
//here you wait for the last thread to finish
{
std::unique_lock<std::mutex> lock(mtx);
cvar.wait(lock, [=]{return n == next;});
}
return(0);
}

如果你可以让你的线程是可连接的,你可以编写更简单的代码。

std::mutex mtx;
std::condition_variable cvar;
long next = 0;
void doit(long index){
std::unique_lock<std::mutex> lock(mtx);
//this guarantees the order in which are being executed
cvar.wait(lock, [=]{return index == next;});
std::cout<< index << std::endl;
++next;
cvar.notify_all();//wakes all the thread, only the one with index=next will be executed
return;
}
int main() 
{
long n=50;
std::vector<std::thread> workers;
for (long i=0; i < n; ++i){
workers.emplace_back(std::thread (doit,i));
}
//this guarantees your threads are all finished at the end of this block
for (auto& t : workers) {
t.join();
}
return(0);
}

为什么不保持简单呢?

int main() {
long n = 50;
std::vector<std::thread> threads;
for (long i = 0; i < n; ++i)
threads.emplace_back([=]() { std::cout << i << std::endl; });
for (const auto& t : threads) {
t.join();
}
return 0;
}

试试这个片段: 你不应该使用 mtx.unlock() 而让condition_variable来完成这项工作。还可以使用 std::ref 将函数参数传递给线程。

std::mutex mtx;
std::condition_variable cvar;
bool ready = true;
void doit(long index) {
std::unique_lock<std::mutex> lock(mtx);
cvar.wait(lock, [=] {return ready == true; });
ready = false;
std::cout << index << std::endl;
ready = true;
cvar.notify_all();
return;
}
int main()
{
long n = 50;
for (long i = 0; i < n; ++i)
std::thread(doit, std::ref(i)).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
return(0);
}

std:: unique_lock是一个RAII对象。在范围内宣布它,并将您的烦恼抛在脑后。问题是:在doit调用mtx.unlock()之后,偶尔下一个语句cvar.notify_all()会立即用(新的)下一个==索引唤醒线程。该线程将获取互斥锁。当 doit 返回时,锁析构函数尝试释放互斥锁,但它被另一个线程持有。灾难接踵而至。这是如何做():

void doit(long index) {
{
std::unique_lock<std::mutex> lock(mtx);
cvar.wait(lock, [=] {return index == next; });
++next;
std::cout << index << std::endl;
}
cvar.notify_all(); 
return;
}

最新更新