資源簡介
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? 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?#“?< 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多線程庫之線程庫使用
評論
共有 條評論