线程构建块上的任务
这是示例代码:
#include <iostream>
#include <list>
#include <tbb/task.h>
#include <tbb/task_group.h>
#include <stdlib.h>
#include <boost/thread.hpp>
using namespace tbb;
long fib(long a)
{
if (a < 2) return 1;
return fib(a - 1) + fib(a - 2);
}
class PrintTask
{
public:
void operator()()
{
std::cout << "hi world!: " << boost::this_thread::get_id() << std::endl;
fib(50);
}
};
int main(int argc, char** argv)
{
task_group group;
for (int i = 0; i < 100; ++i)
{
group.run(PrintTask());
}
group.wait();
return(0);
}
这里我计算一个大的斐波那契序列只是为了模拟非阻塞计算。我预计这段代码会生成两个以上的线程(我的计算机是 Core2Duo),但只调用第一个和第二个任务。这就是被看好的人?
Here is the example code:
#include <iostream>
#include <list>
#include <tbb/task.h>
#include <tbb/task_group.h>
#include <stdlib.h>
#include <boost/thread.hpp>
using namespace tbb;
long fib(long a)
{
if (a < 2) return 1;
return fib(a - 1) + fib(a - 2);
}
class PrintTask
{
public:
void operator()()
{
std::cout << "hi world!: " << boost::this_thread::get_id() << std::endl;
fib(50);
}
};
int main(int argc, char** argv)
{
task_group group;
for (int i = 0; i < 100; ++i)
{
group.run(PrintTask());
}
group.wait();
return(0);
}
Here I'm computing a big fibonacci sequence just to simulate non-blocking computation. I was specting that this code would generate more than two threads (my computer is a Core2Duo), but only the first and second tasks are called. This is the spected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是预期的行为。
TBB 是一个旨在并行化代码以提高性能的库。它不是为异步任务设计的 - 官方文档指出您应该使用另一个库,例如 pthreads,来执行此类任务(或 boost::thread,在您的情况下)。
为了获得最大性能,拥有比内核更多的线程是没有任何意义的,因为涉及到一些显着的开销(不仅是上下文切换,还包括刷新缓存等)。
编辑:
您可以在教程。具体来说,第 1.2 节“好处”中指出
和
Yes, this is the expected behavior.
TBB is a library designed to parallelize code for PERFORMANCE. It is not designed for asynchronous tasks - the official documentation states that you should use another library, eg pthreads, for such tasks (or boost::thread, in your case).
For maximum performance, it does not make any sense to have more threads than you do cores, as there are some significant overheads involved (not just context switching, but also things like flushing the cache).
EDIT:
You can read about it in the Tutorial. Specifically, in section 1.2 "Benefits" it states
and
大规模多线程阻塞行为(std::cout 使用)是多线程中的反模式,可能会导致不良行为,因为这是错误的做法。此外,TBB 保留随心所欲地实现 group.run() 并生成它喜欢的任何线程的权利。如果你只有双核,并且你的调用工作繁重,为什么它应该产生两个以上的线程呢?操作系统和其他应用程序将很乐意吃掉剩余的后台时间。
Massively multithreading blocking behaviour (std::cout use) is an anti-pattern in multithreading and may result in bad behaviour, because it's the wrong thing to do. In addition, TBB reserves the right to implement group.run() however the hell it likes and spawn whatever threads it likes. If you only have a dual core, and you call with heavy work, why should it spawn more than two threads? The OS and other apps will happily eat remaining background time.