MSVC 的并发运行时中的parallel_for_each和parallel_for有什么区别?



parallel_for_each的形式为:

Concurrency::parallel_for_each(start_iterator, end_iterator, function_object);

,但parallel_for也有类似的形式:

Concurrency::parallel_for(start_value, end_value, function_object);

那么Concurrency::parallel_forConcurrency::parallel_for_each算法在多核编程中的区别是什么?

我不知道你说的是什么库,但看起来这个库需要迭代器:

Concurrency::parallel_for_each(start_iterator, end_iterator, function_object);

和可能具有与此相同的效果(尽管顺序不一定相同):

for(sometype i = start_iterator; i != end_iterator; ++i) {
    function_object(*i);
}
例如:

void do_stuff(int x) { /* ... */ }
vector<int> things;
// presumably calls do_stuff() for each thing in things
Concurrency::parallel_for_each(things.begin(), things.end(), do_stuff);

另一个接受值,所以很可能它具有与此类似的效果(但同样没有保证顺序):

for(sometype i = start_value; i != end_value; ++i) {
    function_object(i);
}

试着运行这个:

void print_value(int value) {
    cout << value << endl;
}
int main() {
    // My guess is that this will print 0 ... 9 (not necessarily in order)
    Concurrency::parallel_for(0, 10, print_value);
    return 0;
}

编辑:您可以在并行算法参考中找到这些行为的确认。

最新更新