harmonic_sum

View page source

Multi-Threaded Implementation of Summation of 1/i

Syntax

ok = harmonic_sum ( sum , num_sum )

Purpose

Multi-threaded computation of the summation that defines the harmonic series

\[s = 1 + 1/2 + 1/3 + ... + 1/n\]

Thread

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

ok

This return value has prototype

bool ok

If this return value is false, an error occurred during harmonic .

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\).

num_sum

This argument has prototype

size_t num_sum

It specifies the number of terms in the summation; i.e. \(n\).

Source

namespace {
bool harmonic_sum(double& sum, size_t num_sum)
{  // sum = 1/num_sum + 1/(num_sum-1) + ... + 1
   bool ok = true;
   ok     &= thread_alloc::thread_num() == 0;

   // setup the work for multi-threading
   ok &= harmonic_setup(num_sum);

   // now do the work for each thread
   if( num_threads_ > 0 )
      team_work( harmonic_worker );
   else
      harmonic_worker();

   // combine the result for each thread and takedown the multi-threading.
   ok &= harmonic_takedown(sum);

   return ok;
}
}