简体   繁体   中英

How to add OpenMP for loop by replacing the while loop of a sequential code

the following code is written sequentially. I want to implement OpenMP by replacing while loop to for loop but have no idea how to do this. I know the OpenMP syntax but unable to implement.

The reason to do parallelism is to check the performance between sequential and parallel technique. Any help?

  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 - Can this will be solution?

#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

By implementing the above code

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

The issue is that you have a dependency in your loop. As such, it is not possible to parallelize it as it is.

A good first approach is to use multiple start points and use several threads that will create new hashes. Then when one of the threads finds a good match, you turn a global bool flag and stop all threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM