PracticeDev/study_cpp/mutex/demo2_with_mutex.cpp

46 lines
1.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*************************************************************************
> 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;
}