- 新增现代 C++ 教程的 Preface 章节,包括英文和中文版本 - 添加 C++ Primer 练习代码 - 新增 Learn C++ 教程的 C++ 开发简介章节 - 添加头文件解析文档 - 更新 mkdocs.yml,包含新教程的目录结构 - 修改项目设置,使用 Python 3.10环境
40 lines
823 B
C++
40 lines
823 B
C++
//
|
|
// 7.3.critical.section.b.cpp
|
|
// chapter 7 parallelism and concurrency
|
|
// modern c++ tutorial
|
|
//
|
|
// created by changkun at changkun.de
|
|
// https://github.com/changkun/modern-cpp-tutorial
|
|
//
|
|
|
|
#include <iostream>
|
|
#include <mutex>
|
|
#include <thread>
|
|
|
|
int v = 1;
|
|
|
|
void critical_section(int change_v) {
|
|
static std::mutex mtx;
|
|
std::unique_lock<std::mutex> lock(mtx);
|
|
// do contention operations
|
|
v = change_v;
|
|
std::cout << v << std::endl;
|
|
// release the lock
|
|
lock.unlock();
|
|
|
|
// during this period,
|
|
// others are allowed to acquire v
|
|
|
|
// start another group of contention operations
|
|
// lock again
|
|
lock.lock();
|
|
v += 1;
|
|
std::cout << v << std::endl;
|
|
}
|
|
|
|
int main() {
|
|
std::thread t1(critical_section, 2), t2(critical_section, 3);
|
|
t1.join();
|
|
t2.join();
|
|
return 0;
|
|
} |