使用互斥锁C++程序会提供不可预测的输出。期待死锁,但没有得到它



我有使用互斥进行自我学习的代码。链接为:https://baptiste-wicht.com/posts/2012/04/c11-concurrency-tutorial-advanced-locking-and-condition-variables.html

我写了一个例子:main_deadlock.cpp

#include <iostream>
#include <thread>
#include <mutex>
struct Complex {
std::mutex mutex;
int i;
Complex() : i(0) {}
void mul(int x){
std::cout << "mul : before lock_guard" << std::endl;
std::lock_guard<std::mutex> lock(mutex);
std::cout << "mul : after lock_guard, before operation" << std::endl;
i *= x;
std::cout << "mul : after operation" << std::endl;
}
void div(int x){
std::cout << "div : before lock_guard" << std::endl;
std::lock_guard<std::mutex> lock(mutex);
std::cout << "div : after lock_guard, before operation" << std::endl;
i /= x;
std::cout << "div : after operation" << std::endl;
}
void both(int x, int y)
{
std::cout << "both : before lock_guard" << std::endl;
std::lock_guard<std::mutex> lock(mutex);
std::cout << "both : after lock_guard, before mul()" << std::endl;
mul(x);
std::cout << "both : after mul(), before div()" << std::endl;
div(y);
std::cout << "both : after div()" << std::endl;
}
};
int main(){
std::cout << "main : starting" << std::endl;
Complex complex;
std::cout << "main : calling both()" << std::endl;
complex.both(32, 23);
return 0;
}

我希望这段代码在从both((调用mul((时会出现死锁,因为both(。

现在我使用的是:ubuntu 17.10.1与g++(ubuntu 7.2.0-8ubuntu3.2(7.2.0(g++——版本输出(

如果我正在使用编译命令:

user@user:g++-o out_deadlock main_deadlock.cpp

我一点也不陷入僵局!

但是如果我使用compile命令:

user@user:g++-std=c++11-phread-o out_deadlock main_deadlock.cpp

一切顺利——意味着我看到了僵局。

你能解释一下吗?还有,第一个命令是如何编译代码的?我没有"提到"pthreads,也没有提到-std=c++11,尽管代码使用的是c++11lib?我希望编译/链接失败?

谢谢。

答案是,如果您不编译并链接-pthread,那么您就没有使用实际的pthread锁定函数。

GNU Linux C库是这样设置的,这样库就可以调用所有的锁定函数,但除非它们实际上链接到一个多线程程序中,否则不会发生任何锁定。

最新更新