Elegant exceptionhandling in OpenMP

后端 未结 1 530
执笔经年
执笔经年 2021-02-08 12:38

OpenMP forbids code which leaves the openmp block via exception. Therefore I\'m looking for a nice way of getting the exceptions from an openmp block with the purpose of rethrow

1条回答
  •  攒了一身酷
    2021-02-08 12:53

    You can utilize a few more C++11 tools to clean up the syntax a bit. Add this variadic member function to your ThreadException class:

    class ThreadException {
    
        // ...
    
        template 
        void Run(Function f, Parameters... params)
        {
            try 
            {
                f(params...);
            }
            catch (...)
            {
                CaptureException();
            }
        }
     };
    

    Then when calling inside an OpenMP construct use a lambda function like so:

    ThreadException e;
    
    #pragma omp parallel for
    for (int i = 0; i < n; i++)
    {
        e.Run([=]{
            // code that might throw
            // ...
        });
    }
    e.Rethrow()
    

    0 讨论(0)
提交回复
热议问题