资源简介
c++11多线程库中互斥库模块的使用方式,介绍了mutex类和time_mutex类的使用方式
代码片段和文件信息
#include
#include
#include
namespace mutex_ {
std::mutex mtx; // mutex for critical section
std::timed_mutex tmtx;
static 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 test_mutex_1()
{
std::thread th1(print_block 50 ‘*‘);
std::thread th2(print_block 50 ‘$‘);
th1.join();
th2.join();
return 0;
}
//////////////////////////////////////////////////////
static void print_thread_id(int id)
{
// std::mutex::lock: 锁定线程
// std::mutex::unlock: 解锁线程 releasing ownership over it.
// 临界区:正在锁定的线程具有执行权限:
mtx.lock();
std::cout << “thread #“ << id << ‘\n‘;
mtx.unlock();
}
int test_mutex_2()
{
std::thread threads[10];
// 创建 10个 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_thread_id i + 1);
for (auto& th : threads) th.join();
return 0;
}
volatile int counter(0); // non-atomic counter
static void attempt_10k_increases()
{
// std::mutex::try_lock: 当mutex未锁定时,锁定mutex并返回true
// 如果函数成功锁定线程则返回true 否则返回false.
for (int i = 0; i < 10000; ++i) {
if (mtx.try_lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int test_mutex_3()
{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::
- 上一篇:多线程编程之future库使用
- 下一篇:c++11多线程编程
相关资源
- c++11多线程编程
- c++11原子库
- c++11 bind库使用
- 算术编码c++170579
- C++11标准发布文档
- C++1A2B猜数字游戏
- c++11多线程库之线程库使用
- c++11多线程库之互斥库使用
- c++11的中文文档
- C++入门经典(第10版) Problem Solving
- Concurrency with Modern C++(2019).pdf
- C++11标准完整版ISO+IEC+14882C11;标准
- The Modern C++ Challenge pdf
- Hands-On System Programming with C++17
- visual c++ 14.0安装包
- microsoft visual c++14.0
- Beginning C++17 5th Edition
- C++ mysql查询 C++17编写 可以自动序列化
- C++11/14高级编程Boost程序库探秘中文版
- C++17 - The Complete Guide
- 实用c++100例
- visual c++1200例
评论
共有 条评论