C++11启动线程的多种方式
2017-10-02 15:16
337 查看
1、通过函数指针创建线程
4、通过成员函数创建线程
#include<iostream> #include<thread> using namespace std; void counter(int id,int numIterations) { for(int i=0;i<numIterations;++i) { cout<<"Counter "<<id<<" has value "<<i<<endl; } } int main() { cout.sync_with_stdio(true); thread t1(counter,1,6); thread t2(counter,2,4); t1.join(); t2.join(); return 0; }2、通过函数对象创建线程
#include<iostream> #include<thread> using namespace std; class Counter { public: Counter(int id,int numIterations):mId(id),mNumIterations(numIterations) { } void operator()() const { for(int i=0;i<mNumIterations;++i) { cout<<"Counter "<<mId<<" has value "<<i<<endl; } } protected: int mId; int mNumIterations; }; int main() { cout.sync_with_stdio(true); thread t1{Counter(1,20)};//1.C++11统一初始化语句 Counter c(2,12);//2.定义一个实例,然后传递给thread类的构造函数 thread t2(c); thread t3(Counter(3,10));//3.使用的圆括号 t1.join(); t2.join(); t3.join(); return 0; }3、通过lambda创建线程
#include<iostream> #include<thread> using namespace std; int main() { cout.sync_with_stdio(true); thread t1([](int id,int numIterations) { for(int i=0;i<numIterations;++i) { cout<<"Counter "<<id<<" has value "<<i<<endl; } },1,5); t1.join(); return 0; }
4、通过成员函数创建线程
#include<iostream> #include<thread> using namespace std; class Request { public: Request(int id):mId(id){} void process() { cout<<"Processing request "<<mId<<endl; } protected: int mId; }; int main() { cout.sync_with_stdio(true); Request req(100); thread t{&Request::process,&req}; t.join(); return 0; }
相关文章推荐
- 线程启动的多种方式
- android中 多种启动线程的书写方式及方法
- SE高阶(4):多线程(并发)—①创建启动方式和控制线程方法
- 启动线程的五种方式
- 继承接口Java多线程(二)、启动一个线程的3种方式
- Java 启动线程的方式
- 创建线程的几种方式,以及为什么启动线程不用run,而用start方法!!!
- java中启动线程的两种方式
- Java多线程之两种启动线程方式
- 一个完整的操作UI线程的例子,用到了多种方式
- day10 反射创建数组 线程的基本概念 线程的编写和启动方式 线程的运行状态以及状态转换方法 线程的调度和优先级设置
- 线程 创建和启动线程的两种方式 实现Runnable接口 继承Thread类 重写唯一方法run()
- 第四节:Task的启动的四种方式以及Task、TaskFactory的线程等待和线程延续的解决方案
- Windows中的自动启动项(自动启动的多种方式)
- c++11的多线程支持一(线程启动)
- java多线程2(线程的创建方式以及启动)
- java 启动线程三种方式
- Oracle多种启动方式
- 不同状态下多种启动方式
- ios 线程多种创建方式