46 lines
1.5 KiB
C++
46 lines
1.5 KiB
C++
/*************************************************************************
|
||
> 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;
|
||
}
|