如何通过替换顺序代码的while循环来添加OpenMP for循环

时间:2018-10-25 09:59:36

标签: c++ multithreading c++11 parallel-processing openmp

以下代码按顺序编写。我想通过将while循环替换为for循环来实现OpenMP,但不知道如何执行此操作。我知道OpenMP语法,但是无法实现。

进行并行化的原因是检查顺序技术和并行技术之间的性能。有帮助吗?

  void block::mine_block(uint32_t difficulty) noexcept
{
    string str(difficulty, '0');

    auto start = system_clock::now();

    while (_hash.substr(0, difficulty) != str)
    {
        ++_nonce;
        _hash = calculate_hash();
    }

    auto end = system_clock::now();
    duration<double> diff = end - start;

    cout << "Block mined: " << _hash << " in " << diff.count() << " seconds" << endl;
}

@Matthieu Brucher -这可以解决吗?

#pragma omp parallel    // start the parallel region
{
    #pragma omp single  // let the while loop execute by one thread and generate tasks
    while (time < TotalTime){

        #pragma omp task
        {
            // this code will be a task that may be executed immediately on a different core or deferred for later execution
        }

    } // end of while loop and single region
    // at this point we also wait until all tasks that were created have finished

} // end of parallel region

通过实施上述代码

#pragma omp parallel                        
    {
        #pragma omp single                      
        while (_hash.substr(0, difficulty) != str) {
            #pragma omp task                    
            {
                ++_nonce;
                _hash = calculate_hash();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

问题是您的循环中有一个依赖项。因此,无法按原样对其进行并行化。

第一种好的方法是使用多个起点并使用多个线程来创建新的哈希。然后,当其中一个线程找到合适的匹配项时,您打开一个全局bool标志并停止所有线程。