C++11多线程例子.docx
- 文档编号:2880992
- 上传时间:2022-11-16
- 格式:DOCX
- 页数:24
- 大小:24.43KB
C++11多线程例子.docx
《C++11多线程例子.docx》由会员分享,可在线阅读,更多相关《C++11多线程例子.docx(24页珍藏版)》请在冰豆网上搜索。
C++11多线程例子
Threads
The std:
:
thread classrepresentsathreadofexecutionandisavailableinthe
:
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:
:
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+ 11 多线程 例子