c++11线程库
原始的c标准仅支持单线程编程,新的c标准(c 11或c 0x )于2011年发布,并引入了新的线程库。
编译器要求
Linux: gcc 4.8.1(完全并发支持) () ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )。
windows : visual studio 2012和mingw
如何在linux上编译: g -std=c 11 sample.cpp -lpthread
在c++11中创建线程
每个c APP应用程序都有一个名为main函数的缺省主线程。 在c 11中,可以通过创建std:thread类的对象来创建其他线程,每个std:thread对象可以与一个线程相关联。
必须包含头文件thread
std :: thread对象将执行什么?
可以使用std : thread对象添加回调。 这个新线程开始时执行。 回调包括:
1、函数指针
2、函数对象
3、Lambda函数
线程对象可以这样创建
STD : threadthobj (callback ) ) ) ) ) ) ) )。
新线程在创建新对象后立即开始,并与开始的线程并行执行传递的回调。
此外,任何线程都可以通过在该线程的对象上调用join ()函数来等待另一个线程终止。
让我们看一下主线程创建另一个线程的示例。 创建新线程时,主线程会打印一些信息,并等待新创建的线程结束。
使用函数指针创建线程:
# include iostream # includethreadvoidthread _ function () {for(intI=0; i 100; I ) STD : cout ' threadfunctionexcuting ' STD :3360 endl; }int main () STD:threadthreadobj ) thread_function ); for(intI=0; i 100; I ) STD : cout ' displayfrommainthread ' STD 33603360 endl; threadObj.join (; STD : cout ' exitofmainfunction ' STD :3360 endl; 返回0; }
使用函数对象创建线程:
# include iostream # includethreadclassdisplaythread { public : void operator () () ) for ) intI=0; i 100; I ) STD : cout ' displaythreadexcecuting ' STD :3360 endl; }; int main () STD : threadthreadobj (display thread ) ); for(intI=0; i 100; I ) STD : cout ' displayfrommainthread ' STD 33603360 endl; STD :3360 cout ' waitingforthreadtocomplete ' STD 33603360 endl; threadObj.join (; STD :成本' exitingfrommainthread ' STD :3360 endl; 返回0; }
线程间的区分
每个std:thread对象都有一个关联的可检索id
STD : thread : get _ id ()用成员函数给出对应线程对象的id
STD :3360 this _ thread :3360 get _ id () :给出当前线程的id
如果std:thread对象没有关联的线程,则get_id ) )返回具有默认结构的STD33603360thread33603360id对象: " not any thread "
STD :真: id也可以表示该id
例如:
# include iostream # includethreadvoidthread _ function ((STD : cout ' inside thread 360: thread=' STD 33603603360 ) ) STD : threadthreadobj2(thread _ function ); if(threadobj1.get_id )!=threadObj2.get_id (() STD : cout ' boththreadshavedifferentids ' STD 3360: endl; } STD :3360 cout ' frommainthread :3360 id of thread1=' thread obj1. get _ id (STD 3360: endl; STD : cout ' frommainthread :3360 id of thread2=' thread obj2. get _ id (STD 3360: endl; threadObj1.join (; threadObj2.join (; 返回0; }