多线程是c++中常用的一种技术,可以充分利用多核cpu的计算潜能.以下以相关概念介绍多线程的使用.
线程(thread)与进程(process)均为音译词,进程本质上就是广义上理解的程序,而进程则是一个程序内部的一种并行计算方法.最常见的,在ros中,node与node之间的关系,就是进程.而在一个node中,订阅两个消息去处理,则是两个线程.
多线程的实现一般有三种方式:函数指针,functor,lambda表达式
2.1 函数指针的方式 以下为一个累加函数的实现,输入向量、累加变量、首尾序号 void accumulator_function2(const std::vector<int> &v, unsigned long long &acm, unsigned int beginIndex, unsigned int endIndex) { acm = 0; for (unsigned int i = beginIndex; i < endIndex; ++i) { acm += v[i]; } }那实现多线程的方式如下:
//Pointer to function { unsigned long long acm1 = 0; unsigned long long acm2 = 0; std::thread t1(accumulator_function2, std::ref(v), std::ref(acm1), 0, v.size() / 2); std::thread t2(accumulator_function2, std::ref(v), std::ref(acm2), v.size() / 2, v.size()); t1.join(); t2.join(); std::cout << "acm1: " << acm1 << endl; std::cout << "acm2: " << acm2 << endl; std::cout << "acm1 + acm2: " << acm1 + acm2 << endl; }大体思想是,将一个数组一分为二,使用两个线程去计算。线程t1和t2中传进去的acm1、acm2,不能是同一个数,如果是同一个,就会发生两个线程同时修改一个变量的错误。 几个基本语法:std::thread表示新建一个线程;join表示执行该线程
2.2 functor的方式 同样的,先定义一个functor,然后再定义多线程去调用: class CAccumulatorFunctor3 { public: void operator()(const std::vector<int> &v, unsigned int beginIndex, unsigned int endIndex) { _acm = 0; for (unsigned int i = beginIndex; i < endIndex; ++i) { _acm += v[i]; } } unsigned long long _acm; }; //Creating Thread using Functor { CAccumulatorFunctor3 accumulator1 = CAccumulatorFunctor3(); CAccumulatorFunctor3 accumulator2 = CAccumulatorFunctor3(); std::thread t1(std::ref(accumulator1), std::ref(v), 0, v.size() / 2); std::thread t2(std::ref(accumulator2), std::ref(v), v.size() / 2, v.size()); t1.join(); t2.join(); std::cout << "acm1: " << accumulator1._acm << endl; std::cout << "acm2: " << accumulator2._acm << endl; std::cout << "accumulator1._acm + accumulator2._acm : " << accumulator1._acm + accumulator2._acm << endl; } 2.3 lambda表达式的方式 { unsigned long long acm1 = 0; unsigned long long acm2 = 0; std::thread t1([&acm1, &v] { for (unsigned int i = 0; i < v.size() / 2; ++i) { acm1 += v[i]; } }); std::thread t2([&acm2, &v] { for (unsigned int i = v.size() / 2; i < v.size(); ++i) { acm2 += v[i]; } }); t1.join(); t2.join(); std::cout << "acm1: " << acm1 << endl; std::cout << "acm2: " << acm2 << endl; std::cout << "acm1 + acm2: " << acm1 + acm2 << endl; }这种适合处理流程比较简单的多线程任务。
包括:线程间同步,线程间互斥,死锁。将在后续文章中进行解说。
