PracticeDev/study_cpp/mutex/demo1_no_mutex.cpp

36 lines
1.0 KiB
C++
Raw Normal View History

2022-12-20 17:31:11 +08:00
/*************************************************************************
> File Name : demo1.cpp
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Mon Feb 8 08:45:37 2021
************************************************************************/
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <chrono>
#include <stdexcept>
int counter = 0;
void increase(int time) {
for (int i = 0; i < time; i++) {
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
}
}
/*
* "counter++"线
* https://zhuanlan.zhihu.com/p/91062516
*/
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;
}