蓝桥ROS机器人之现代C++学习笔记7.2 互斥量与临界区
Posted zhangrelay
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了蓝桥ROS机器人之现代C++学习笔记7.2 互斥量与临界区相关的知识,希望对你有一定的参考价值。
看如下三段代码:
// mutex example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
std::mutex mtx; // mutex for critical section
void print_block (int n, char c)
// critical section (exclusive access to std::cout signaled by locking mtx):
mtx.lock();
for (int i=0; i<n; ++i) std::cout << c;
std::cout << '\\n';
mtx.unlock();
int main ()
std::thread th1 (print_block,50,'*');
std::thread th2 (print_block,50,'$');
th1.join();
th2.join();
return 0;
#include <iostream>
#include <mutex>
#include <thread>
int v = 1;
void critical_section(int change_v)
static std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);
// do contention operations
v = change_v;
// mtx will be destructed when exit this region
int main()
std::thread t1(critical_section, 2), t2(critical_section, 3);
t1.join();
t2.join();
std::cout << v << std::endl;
return 0;
#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;
尝试编译无果……
查一下,c++20应该可以。
只能使用如下链接:
coliru.stacked-crooked.com
01
02
03
以上是关于蓝桥ROS机器人之现代C++学习笔记7.2 互斥量与临界区的主要内容,如果未能解决你的问题,请参考以下文章