C++11多线程例子.docx

上传人:b****5 文档编号:2880992 上传时间:2022-11-16 格式:DOCX 页数:24 大小:24.43KB
下载 相关 举报
C++11多线程例子.docx_第1页
第1页 / 共24页
C++11多线程例子.docx_第2页
第2页 / 共24页
C++11多线程例子.docx_第3页
第3页 / 共24页
C++11多线程例子.docx_第4页
第4页 / 共24页
C++11多线程例子.docx_第5页
第5页 / 共24页
点击查看更多>>
下载资源
资源描述

C++11多线程例子.docx

《C++11多线程例子.docx》由会员分享,可在线阅读,更多相关《C++11多线程例子.docx(24页珍藏版)》请在冰豆网上搜索。

C++11多线程例子.docx

C++11多线程例子

Threads

The std:

:

thread classrepresentsathreadofexecutionandisavailableinthe  header. std:

:

thread canworkwithregularfunctions,lambdasandfunctors(aclassimplementingoperator()).Moreoveritallowsyoutopassanynumberofparameterstothethreadfunction. 

 Collapse | CopyCode

#include

voidfunc()

{

//dosomework

}

intmain()

{

std:

:

threadt(func);

t.join();

return0;

}

Inthisexample t isathreadobjectrepresentingthethreadunderwhichfunction func() runs.Thecallto join blocksthecallingthread(inthiscasethemainthread)untilthejoinedthreadfinishesexecution.Ifthethreadfunctionreturnsavalue,itisignored.However,thefunctioncantakeanynumberofparameters.

 Collapse | CopyCode

voidfunc(inti,doubled,conststd:

:

string&s)

{

std:

:

cout<

:

endl;

}

intmain()

{

std:

:

threadt(func,1,12.50,"sample");

t.join();

return0;

}

Eventhoughit'spossibletopassanynumberofparameterstothethreadfunction,allparametersarepassedbyvalue.Ifthefunctionneedstotakeparametersbyreference,thepassedargumentsmustbewrappedina std:

:

reforstd:

:

creflikeinthefollowingexample.

 Collapse | CopyCode

voidfunc(int&a)

{

a++;

}

intmain()

{

inta=42;

std:

:

threadt(func,std:

:

ref(a));

t.join();

std:

:

cout<

:

endl;

return0;

}

Theprogramprints43,butwithoutwrappingaina std:

:

ref theoutputwouldbe42.

Apartfromthejoinmethod,thethreadclassprovidesacouplemoreoperations:

∙swap:

exchangestheunderlyinghandlesoftwothreadobjects

∙detach:

allowsathreadofexecutiontocontinueindependentlyofthethreadobject.Detachedthreadsarenolongerjoinable(youcannotwaitforthem).

 Collapse | CopyCode

intmain()

{

std:

:

threadt(funct);

t.detach();

return0;

}

Animportantthingtonoteisthatifathreadfunctionthrowsanexceptionitwon'tbecaughtwitharegulartry-catchblock.Inotherwords,thiswon'twork:

 Collapse | CopyCode

try

{

std:

:

threadt1(func);

std:

:

threadt2(func);

t1.join();

t2.join();

}

catch(conststd:

:

exception&ex)

{

std:

:

cout<

:

endl;

}

Topropagateexceptionsbetweenthreadsyoucouldcatchtheminthethreadfunctionandstoretheminaplacewhereitcanbeaccessedlater.

 Collapse | CopyCode

std:

:

mutexg_mutex;

std:

:

vector

:

exception_ptr>g_exceptions;

voidthrow_function()

{

throwstd:

:

exception("somethingwronghappened");

}

voidfunc()

{

try

{

throw_function();

}

catch(...)

{

std:

:

lock_guard

:

mutex>lock(g_mutex);

g_exceptions.push_back(std:

:

current_exception());

}

}

intmain()

{

g_exceptions.clear();

std:

:

threadt(func);

t.join();

for(auto&e:

g_exceptions)

{

try

{

if(e!

=nullptr)

{

std:

:

rethrow_exception(e);

}

}

catch(conststd:

:

exception&e)

{

std:

:

cout<

:

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 表格模板 > 调查报告

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1