资源简介
c++多线程库的使用demo,介绍了互斥库 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;
}
//////////////////////////////////////////////////////
// reference: http://www.cplusplus.com/reference/mutex/mutex/lock/
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
- 上一篇:MFC下配置opengl环境具体步骤
- 下一篇:c++11多线程库之线程库使用
评论
共有 条评论