1 std::lock_guard 的特点
1,异常安全
2,不可复制和不可移动, 这确保了对mutex锁的独占性,避免锁状态不一致
3, 单一责任, 仅用于管理mutex锁的锁定和解锁,不支持其他锁定策略
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
using namespace std;
int myCount = 0;
int myCount1 = 0;
mutex myMutex;
void own() {
{
lock_guard<mutex> lock(myMutex);
for(size_t i = 0; i<100000; i++) {
myCount++;
}
}
for(size_t i = 0; i<100000; i++) {
myCount1++;
}
}
int main() {
std::cout << "Hello, World!" << std::endl;
vector<thread> myBox;
for (int i = 0; i < 10; i++) {
myBox.emplace_back(own);
}
for(thread& t:myBox) {
t.join();
}
printf("myCount: %d\n", myCount);
printf("myCount1: %d", myCount1);
return 0;
}