C/C++编程:锁的应用
C++11中std::unique_lock的使用
给一个互斥的例子:
加锁前:
#include <iostream>
#include <vector>
#include <unordered_set>
#include "atomic_ops.h"
#include <thread>
#include <mutex>
using namespace std;
std::mutex supernode_ids_mux_;
void testA(){
// std::unique_lock<std::mutex> lk(supernode_ids_mux_);
int i = 10;
while (i--){
cout << "testA----" << endl;
}
}
void testB(){
// std::unique_lock<std::mutex> lk(supernode_ids_mux_);
int i = 10;
while (i--){
cout << "testB====" << endl;
}
}
int main()
{
std::thread t1(testA);
std::thread t2(testB);
t1.join();
t2.join();
return 0;
}
运行命令:
g++ test2.cc -fopenmp && ./a.out
运行结果:
testB====testA----
testA----testB====
testB====
testB====
testB====
testB====
testB====
testB====
testB====
testB====
testA----
testA----
testA----
testA----
testA----
testA----
testA----
testA----
加锁后:
#include <iostream>
#include <vector>
#include <unordered_set>
#include "atomic_ops.h"
#include <thread>
#include <mutex>
using namespace std;
std::mutex supernode_ids_mux_;
void testA(){
std::unique_lock<std::mutex> lk(supernode_ids_mux_);
int i = 10;
while (i--){
cout << "testA----" << endl;
}
}
void testB(){
std::unique_lock<std::mutex> lk(supernode_ids_mux_);
int i = 10;
while (i--){
cout << "testB====" << endl;
}
}
int main()
{
std::thread t1(testA);
std::thread t2(testB);
t1.join();
t2.join();
return 0;
}
运行结果:
testA----
testA----
testA----
testA----
testA----
testA----
testA----
testA----
testA----
testA----
testB====
testB====
testB====
testB====
testB====
testB====
testB====
testB====
testB====
testB====