PracticeDev/study_cpp/mutex/demo2_with_mutex.cpp

46 lines
1.5 KiB
C++
Raw Normal View History

2022-12-20 17:31:11 +08:00
/*************************************************************************
> File Name : demo2.cpp
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Mon Feb 8 08:49:23 2021
************************************************************************/
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <chrono>
#include <stdexcept>
int counter = 0;
std::mutex mtx; // 保护counter
void increase(int time) {
for (int i = 0; i < time; i++) {
mtx.lock();
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
mtx.unlock();
}
}
/*
*
* 1. std::mutex对象线
* 2. mtx.lock()线
* 线线block
* mtx.unlock()
* 3. mtx.unlock()4. std::mutex还有一个操作mtx.try_lock()
* mtx.lock()线
*/
int main(int argc, char** argv) {
std::thread t1(increase, 10000);
std::thread t2(increase, 10000);
t1.join();
t2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}