我有一个双核处理器,根据解释,我只能使用2个线程,但实际上我可以同时启动2个以上的线程:
以下是解释的副本:
boost :: thread类提供的静态hardware_concurrency()方法根据底层的CPU或CPU核心数返回可以在物理上同时执行的线程数.在常用的双核机器上调用此函数,返回值2.这允许一种简单的方法来识别给定多线程应用程序应同时使用的理论最大线程数.
在我的情况下,hardware_concurrency()方法返回数字2,但是该程序同时使用4个线程:
#include <iostream>
#include <boost\thread.hpp>
using namespace std;
using boost::thread;
using namespace boost::this_thread;
using boost::posix_time::seconds;
void f1()
{
for(int i = 0; i < 10; ++i)
{
cout << i << endl;
sleep(seconds(2));
}
}
void f2()
{
for(int i = 0; i < 10; ++i)
{
cout << i << endl;
sleep(seconds(2));
}
}
int main()
{
// 4 threads are executed on dual core machine (no problem)
thread thr1(f1);
thread thr2(f2);
thread thr3(f1); …Run Code Online (Sandbox Code Playgroud)