Prev Next harmonic_takedown

@(@\newcommand{\W}[1]{ \; #1 \; } \newcommand{\R}[1]{ {\rm #1} } \newcommand{\B}[1]{ {\bf #1} } \newcommand{\D}[2]{ \frac{\partial #1}{\partial #2} } \newcommand{\DD}[3]{ \frac{\partial^2 #1}{\partial #2 \partial #3} } \newcommand{\Dpow}[2]{ \frac{\partial^{#1}}{\partial {#2}^{#1}} } \newcommand{\dpow}[2]{ \frac{ {\rm d}^{#1}}{{\rm d}\, {#2}^{#1}} }@)@
Take Down Multi-threading Sum of 1/i

Syntax
ok = harmonic_takedown(sum)

Purpose
This routine does the takedown for splitting the summation that defines the harmonic series @[@ s = 1 + 1/2 + 1/3 + ... + 1/n @]@ into separate parts for each thread; see harmonic_setup .

Thread
It is assumed that this function is called by thread zero, and all the other threads have completed their work and are blocked (waiting).

sum
This argument has prototype
     double& 
sum
The input value of the argument does not matter. Upon return it is the value of the summation; i.e. @(@ s @)@.

Source

namespace {
bool harmonic_takedown(double& sum)
{     // sum = 1/num_sum + 1/(num_sum-1) + ... + 1
     bool ok            = true;
     ok                &= thread_alloc::thread_num() == 0;
     size_t num_threads = std::max(num_threads_, size_t(1));
     sum                = 0.;
     //
     // go down so that free memory for other threads before memory for master
     size_t thread_num = num_threads;
     while(thread_num--)
     {     // check that this tread was ok with the work it did
          ok  &= work_all_[thread_num]->ok;
          //
          // add this threads contribution to the sum
          sum += work_all_[thread_num]->sum;
          //
          // delete problem specific information
          void* v_ptr = static_cast<void*>( work_all_[thread_num] );
          thread_alloc::return_memory( v_ptr );
          //
          // check that there is no longer any memory inuse by this thread
          // (for general applications, the master might still be using memory)
          ok &= thread_alloc::inuse(thread_num) == 0;
          //
          // return all memory being held for future use by this thread
          thread_alloc::free_available(thread_num);
     }
     return ok;
}
}

Input File: example/multi_thread/harmonic.cpp