資源簡(jiǎn)介
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? 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.
//?臨界區(qū):正在鎖定的線程具有執(zhí)行權(quán)限:
mtx.lock();
std::cout?<“thread?#“?< mtx.unlock();
}
int?test_mutex_2()
{
std::thread?threads[10];
//?創(chuàng)建?10個(gè)?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:?當(dāng)mutex未鎖定時(shí),鎖定mutex并返回true
//?如果函數(shù)成功鎖定線程則返回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多線程編程
評(píng)論
共有 條評(píng)論