蓝桥ROS机器人之现代C++学习笔记7.2 互斥量与临界区

蓝桥ROS机器人之现代C++学习笔记7.2 互斥量与临界区,第1张

看如下三段代码:

// mutex example
#include        // std::cout
#include          // std::thread
#include           // 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

#include 
#include 
#include 

int v = 1;

void critical_section(int change_v) {
    static std::mutex mtx;
    std::lock_guard 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 
#include 
#include 

int v = 1;

void critical_section(int change_v) {
    static std::mutex mtx;
    std::unique_lock 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 


 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/728587.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)