std::get<C++11多线程库~线程管理>(09):运行时决定线程数量

 1 #include <QCoreApplication>
 2 #include <thread>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <vector>
 6 
 7 /*
 8  * 话题1: 运行时决定线程的数量。
 9  *        线程的数量并非越多越好,线程间的上下文切换是需要时间开销的,保存线程的上下文是需要空间开销的。
10  *
11  *        那一个进程到底拥有几个线程比较合理,需根据实际情况处理。 这里讲一个非常有用的函数:std::thread::hardware_concurrency()
12  *        该函数可以获取一个应用程序最多支持的线程数量。
13 */
14 struct run{
15     run(short id):m_id(id){}
16     void operator()(){
17         std::cout<<"run id is "<<m_id<<std::endl;
18     }
19 
20 private:
21     short m_id;
22 };
23 
24 int main(int argc, char *argv[])
25 {
26     QCoreApplication a(argc, argv);
27 
28     unsigned long const hardware_num = std::thread::hardware_concurrency();
29     std::cout<<"hardware number is = "<<hardware_num<<std::endl;
30 
31     unsigned long const thread_num_max = 5;
32     unsigned long thread_num = std::min(hardware_num, thread_num_max);
33     std::vector<std::thread> threads;
34     for (; thread_num; --thread_num){
35         threads.push_back(std::thread(run(thread_num)));
36     }
37     std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
38     return a.exec();
39 }

#include<QCoreApplication>
#include<thread>
#include<iostream>
#include<algorithm>
#include<vector>

/*
*话题1:运行时决定线程的数量。
*线程的数量并非越多越好,线程间的上下文切换是需要时间开销的,保存线程的上下文是需要空间开销的。
*
*那一个进程到底拥有几个线程比较合理,需根据实际情况处理。这里讲一个非常有用的函数:std::thread::hardware_concurrency()
*该函数可以获取一个应用程序最多支持的线程数量。
*/
structrun{
run(shortid):m_id(id){}
voidoperator()(){
std::cout<<"runidis"<<m_id<<std::endl;
}

private:
shortm_id;
};

intmain(intargc,char*argv[])
{
QCoreApplicationa(argc,argv);

unsignedlongconsthardware_num=std::thread::hardware_concurrency();
std::cout<<"hardwarenumberis="<<hardware_num<<std::endl;

unsignedlongconstthread_num_max=5;
unsignedlongthread_num=std::min(hardware_num,thread_num_max);
std::vector<std::thread>threads;
for(;thread_num;--thread_num){
threads.push_back(std::thread(run(thread_num)));
}
std::for_each(threads.begin(),threads.end(),std::mem_fn(&std::thread::join));
returna.exec();
}

原文地址:https://www.cnblogs.com/azbane/p/15366443.html