使用TBB进行非并行任务 [英] using TBB for non-parallel tasks
问题描述
我想使用TBB获得线程池行为.但是,每当我阅读有关TBB的文档时,他们总是谈论并发,并发等.相反,我需要的是一个主线程,将任务分配给线程池,以便这些任务将独立"执行-执行任务异步地.此处的任务可以是GUI的事件处理.
I want to get a thread-pool behavior using TBB. But whenever I read documents about TBB they always talk about parallel-for, parallel-dowhile etc. In contrast what I need is a main thread to assign tasks to a thread pool so those tasks will be executed 'on their own' - execute tasks asynchronously. Tasks here can be event handling for a GUI.
TBB任务计划程序是否适合这种行为?从任务计划程序获得的印象是,只有当我具有可以分解并彼此并行执行的任务时,这才是有益的.
Is the TBB task scheduler appropriate for such behavior? The impression I got from task scheduler is that it's only beneficial if I have tasks that can be broken down and executed in parallel to each other.
推荐答案
从版本3.0开始,TBB支持异步执行任务.为此,添加了一种特殊的工作提供方法tbb::task::enqueue()
.与tbb::task::spawn()
不同,此方法保证即使始发线程从不输入任务分配方法(例如wait_for_all()
),也将执行排队的任务.
Starting from version 3.0, TBB has support for asynchronous execution of tasks. For that, a special work offering method tbb::task::enqueue()
was added. Unlike tbb::task::spawn()
, this method guarantees that the enqueued task will be executed even if the originating thread never enters a task dispatch method such as wait_for_all()
.
task::enqueue()
的简短用法示例:
class MyTask : public tbb::task {
/*override*/ tbb::task* execute() {
// Do the job
return NULL; // or a pointer to a new task to be executed immediately
}
};
MyTask* t = new (tbb::task::allocate_root()) MyTask();
tbb::task::enqueue(*t);
// Do other job; the task will be executed asynchronously
如注释中提到的@JimMishell,可以在设计模式"中找到如何使用它来处理GUI事件的示例.并且该方法的正式说明可在参考手册中找到(两者均请参见 TBB文档).
As @JimMishell mentioned in the comment, an example how to use it for handling of GUI events can be found in "Design Patterns"; and the formal description of the method is available in the Reference manual (see TBB documentation for both).
这篇关于使用TBB进行非并行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!