std::get(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 }

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

 

 

 

 

 

#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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/398279

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月12日 上午9:36
下一篇 2023年4月12日 上午9:36

相关推荐