我有一个双核心处理器,根据说明我只能使用2个线程,但实际上我能够同时启动2个以上的线程:双核心机器上的多线程?
这里是一个解释的副本:
静态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);
thread thr4(f2);
cin.ignore();
return 0;
}
任何人都可以解释这种行为?
,只要你想(到了极限)可以使尽可能多的线程,但2完成(可能)最佳数量,每个核心一个。另外,它说“同时实际执行”。你可以超过2个,但他们不会同时运行;操作系统将不得不抢先运行,让其他人运行。另外,它说“应该”,而不是“可以”。 – 2012-01-10 20:02:26
以及在双核机器上使用例如10个线程应用程序会产生哪些副作用?那是不是好?非常感谢。 – codekiddy 2012-01-10 20:04:39
副作用(可能)仅限于您的应用程序运行速度较慢(因为操作系统不得不担心让每个其他线程都有时间运行,其中有2个,它可以让它们全速运行),尽管这可能会抵消通过能够“同时”做更多(不是一次,而是独立)。 – 2012-01-10 20:05:45