并发阵列检查

时间:2017-08-11 10:24:38

标签: c++ multithreading concurrency parallel-processing

我既不是C ++专家,也不是并发编程专家。但是,我正在实现一个简单的推理算法,需要检查许多独立模型。可能的模型数量巨大,所以我想并行检查它们。

为了使其尽可能简单,我将原始问题转换为一个非常简单的问题:如何确定数组是否包含非零值?一个简单的顺序解决方案是这样的:

bool containsNonZero (int* arr, int len) {
    for (int i = 0; i < len; ++i)
        if (arr[i]) return true;
    return false;
}

(注意:实际上, len 不能适合 int ,但在我原来的问题中,没有数组,只有我生成的很多组合但是不存储。)

但是,我需要一个并行(和有效)的实现。有 t = std :: thread :: hardware_concurrency()线程来搜索数组(注意 t &lt;&lt; len 。如果 len%t!= 0 那么让最后一个线程处理其余的值不会有问题)。所以第一个线程将搜索从 0 len / t 的索引,第二个线程将搜索从 len / t 到(2)的索引* len)/ t等。最后一个线程将搜索从((t-1)* len)/ t到 len 的索引。如果线程找到非零值,则所有线程都将停止并返回 true 。否则,他们将等待其他人完成,如果所有线程都同意,将返回 false

看起来很简单,但我无法在网上找到任何答案。欢迎任何C ++版本,但我不想依赖任何第三方库。

2 个答案:

答案 0 :(得分:2)

我试图扩展Davide Spataro的解决方案以解决使用atomic<bool>的{​​{1}}同步问题,其中'与std :: atomic的所有特化不同,它保证无锁'{ {3}}

编辑: 与之前的问题无关,但我已经确定了哪种方法更快,我感到惊讶的是atomic_flagatomic<bool>快了大约100。

基准测试结果:

atomic_flag

基准代码:

num_threads:2
400000001 iterations flag
401386195 iterations flag
atomic_flag : it took 24.1202 seconds. Result: 1
400000001 iterations bool
375842699 iterations bool
atomic<bool>: it took 0.334785 seconds. Result: 1
num_threads:3
229922451 iterations flag
229712046 iterations flag
233333335 iterations flag
atomic_flag : it took 21.5974 seconds. Result: 1
219564626 iterations bool
233333335 iterations bool
196877803 iterations bool
atomic<bool>: it took 0.200942 seconds. Result: 1
num_threads:4
151745683 iterations flag
150000001 iterations flag
148849108 iterations flag
148933269 iterations flag
atomic_flag : it took 18.6651 seconds. Result: 1
150000001 iterations bool
112825220 iterations bool
151838008 iterations bool
112857688 iterations bool
atomic<bool>: it took 0.167048 seconds. Result: 1

旧帖子: 我对迭代器的常量和放置线程有一些问题,但核心更改,即atomic_flag的使用似乎有效。它不会立即停止所有线程,但在最坏的情况下每次迭代只有一个(因为每次迭代只有一个线程会知道它应该因为清除标志而已经停止)。

#include <thread>
#include <atomic>
#include <vector>
#include <iostream>
#include <algorithm>



template<typename Iterator>
static void any_of_flag(Iterator & begin, Iterator& end, std::atomic_flag & result)
{
    int counter = 0;
    for (auto it = begin; it != end; ++it)
    {
        counter++;
        if (!result.test_and_set() || (*it) != 0)
        {
            result.clear();
            std::cout << counter << " iterations flag\n";
            return;
        }
    }
}
template<typename Iterator>
static void any_of_atomic(Iterator & begin, Iterator& end, std::atomic<bool> & result)
{
    int counter = 0;
    for (auto it = begin; it != end; ++it)
    {
        counter++;
        if (result || (*it) != 0)
        {
            result = true;
            std::cout << counter << " iterations bool\n";
            return;
        }
    }
}

void test_atomic_flag(std::vector<int>& input, int num_threads)
{

    using namespace std::chrono;

    high_resolution_clock::time_point t1 = high_resolution_clock::now();


    size_t chunk_size = input.size() / num_threads;
    std::atomic_flag result = ATOMIC_FLAG_INIT;
    result.test_and_set();

    std::vector<std::thread> threads;
    for (size_t i = 0; i < num_threads; ++i)
    {
        auto & begin = input.begin() + i *chunk_size;
        auto & end = input.begin() + std::min((i + 1) * chunk_size, input.size());
        // had to use lambda in VS 2017
        threads.emplace_back([&begin, &end, &result] {any_of_flag(begin, end, result); });

    }

    for (auto & thread : threads)
        thread.join();

    bool hasNonZero = !result.test_and_set();


    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

    std::cout << "atomic_flag : it took " << time_span.count() << " seconds. Result: " << hasNonZero << std::endl;
}



void test_atomic_bool(std::vector<int>& input, int num_threads)
{

    using namespace std::chrono;

    high_resolution_clock::time_point t1 = high_resolution_clock::now();


    size_t chunk_size = input.size() / num_threads;
    std::atomic<bool> result(false);

    std::vector<std::thread> threads;
    for (size_t i = 0; i < num_threads; ++i)
    {
        auto & begin = input.begin() + i *chunk_size;
        auto & end = input.begin() + std::min((i + 1) * chunk_size, input.size());
        // had to use lambda in VS 2017
        threads.emplace_back([&begin, &end, &result] {any_of_atomic(begin, end, result); });

    }

    for (auto & thread : threads)
        thread.join();

    bool hasNonZero = result;


    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

    std::cout << "atomic<bool>: it took " << time_span.count() << " seconds. Result: " << hasNonZero << std::endl;
}

int main()
{
    std::vector<int> input(1e9, 0);
    input[1e9 - 1e8] = 1;
    for (int num_threads : {2, 3, 4})
    {
        std::cout << "num_threads:" << num_threads << std::endl;
        test_atomic_flag(input, num_threads);
        test_atomic_bool(input, num_threads);
    }

    int q;
    std::cin >> q;
    return 0;
};

答案 1 :(得分:1)

如下所示:

每个工作人员检查天气,其范围内的元素是非零,或者是否设置了原子标志(意味着其他一些线程已找到它)。

以下是每个线程执行的功能(每个线程都分配了一个差值范围)

 template<typename Iterator>
static void any_of(Iterator & begin, Iterator& end, std::atomic<bool> & result) 
    {
        for (const auto & it=begin; it!=end; ++it)
        {
            if (result || (*it)!=0)
            {
                result= true;
                return;
            }
       }

您可以按如下方式调用

size_t chunk_size = input.size() / num_threads;
std::atomic<bool> result(false);
std::vector<std::thread> threads;
for (size_t i = 0; i < num_threads; ++i)
{
    const auto & begin = input.begin() + i *chunk_size;
    const auto & end = input.begin() + std::min((i+1) * chunk_size, input.size());
    threads.emplace_back(any_element_of,begin,end,result);
}

for (auto & thread : threads)
    thread.join();

在此之后,您可以安全地检查return以检索结果。

请注意,通过将一元谓词函数传递给worker以使其更通用,可以轻松扩展此方法。

 template<typename Iterator, typename Predicate>
static void any_of(Iterator & begin, Iterator& end, Predicate pred, std::atomic<bool> & result) 
    {
        for (const auto & it=begin; it!=end; ++it)
        {
            if (result || pred(*it))
            {
                result= true;
                return;
            }
       }