:
endl;
}
}
return0;
}
Formoreinformationaboutcatchingandpropagatingexceptionsyoucanread HandlingC++exceptionsthrownfromworkerthreadinthemainthread and HowcanIpropagateexceptionsbetweenthreads?
.
Beforegoingfurtheritworthnotingthatthe headerprovidessomehelperfunctionsinnamespacestd:
:
this_thread:
∙get_id:
returnstheidofthecurrentthread
∙yield:
tellstheschedulertorunotherthreadsandcanbeusedwhenyouareinabusywaitingstate
∙sleep_for:
blockstheexecutionofthecurrentthreadforatleastthespecifiedperiod
∙sleep_util:
blockstheexecutionofthecurrentthreaduntilthespecifiedmomentoftimehasbeenreached
Locks
InthelastexampleIneededtosynchronizetheaccesstothe g_exceptions vectortomakesureonlyonethreadatatimecanpushanewelement.ForthisIusedamutexandalockonthemutex.AmutexisacoresynchronizationprimitiveanditC++11itcomesinfourflavorsinthe header.
∙mutex:
providesthecorefunctions lock() and unlock() andthenon-blocking try_lock() methodthatreturnsifthemutexisnotavailable.
∙recursive_mutex:
allowsmultipleacquisitionsofthemutexfromthesamethread.
∙timed_mutex:
similartomutex,butitcomeswithtwomoremethods try_lock_for() and try_lock_until() thattrytoacquirethemutexforaperiodoftimeoruntilamomentintimeisreached.
∙recursive_timed_mutex:
isacombinationoftimed_mutexandrecusive_mutex.
Hereisanexampleforusinga std:
:
mutex (noticetheuseofthe get_id() and sleep_for() helperfunctionsmentionedearlier).
Collapse | CopyCode
#include
#include
#include
#include
std:
:
mutexg_lock;
voidfunc()
{
g_lock.lock();
std:
:
cout<<"enteredthread"<:
this_thread:
:
get_id()<:
endl;
std:
:
this_thread:
:
sleep_for(std:
:
chrono:
:
seconds(rand()%10));
std:
:
cout<<"l