【cmu15445c++入门】(10)C++锁mutex

 一、锁

lock和unlock

二、 代码


// This program shows a small example of the usage of std::mutex. The
// std::mutex class provides the mutex synchronization primitive.
// std::mutex 类提供互斥同步原语。

// Includes std::cout (printing) for demo purposes.
#include <iostream>
// Includes the mutex library header.
#include <mutex>
// Includes the thread library header.
#include <thread>

// Defining a global count variable and a mutex to be used by both threads.
int count = 0;

// This is the syntax for declaring and default initializing a mutex.
std::mutex m;

// The add_count function allows for a thread to increment the count variable
// by 1, atomically.
void add_count() {
  // Acquire the lock before accessing count, the shared resource.
  m.lock();
  count += 1;
  // Release the lock after accessing count, the shared resource.
  m.unlock();
}

// The main method constructs two thread objects and has them both run the
// add_count function in parallel. After these threads are finished executing,
// we print the count value, showing that both increments worked successfully.
// The std::thread library is the C++ STL library used to construct threads.
// You may view it as a C++ equivalent of the pthread library in C.
// main 方法构造两个线程对象,并让它们同时运行 add_count 函数。
// 这些线程执行完毕后,我们打印计数值,表明两个增量都成功工作。  
// std::thread 库是用于构造线程的 C++ STL 库
// 您可以将其视为 C 中 pthread 库的 C++ 等效项。

int main() {
  std::thread t1(add_count);
  std::thread t2(add_count);
  t1.join();
  t2.join();

  std::cout << "Printing count: " << count << std::endl;
  return 0;
}

三、运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

康雨城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值