Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a widely used multiprocessing abstraction library available for c++?

I'm coming from Python and heading into C++ at full-throttle. And, one of the questions that I came up with recently is this: Is there a widely used open source multiprocessing abstraction library in C++? I'm thinking of something that makes multiprocessing (ala fork) a bit easier to manage, similar to Python's multiprocessing stdlib library.

I guess there isn't anything like this. I fully expected there to be a Boost::Process just like there is a Boost::Thread.

like image 205
bitcycle Avatar asked Nov 03 '22 05:11

bitcycle


1 Answers

OpenMP (Open Multi-Processing) is the only library I know of http://en.wikipedia.org/wiki/OpenMP -- it does not however, handle things the way Python does by creating new processes. OpenMP is a compiler extension, supported by Microsoft and GNU GCC.

Example: OpenMP sieve of eratosthenes

// odd-only sieve
int eratosthenesOdd(int lastNumber, bool useOpenMP)
{
  // enable/disable OpenMP
  omp_set_num_threads(useOpenMP ? omp_get_num_procs() : 1);
  // instead of i*i <= lastNumber we write i <= lastNumberSquareRoot to help OpenMP
  const int lastNumberSqrt = (int)sqrt((double)lastNumber);
  int memorySize = (lastNumber-1)/2;
  // initialize
  char* isPrime = new char[memorySize+1];
  #pragma omp parallel for
  for (int i = 0; i <= memorySize; i++)
    isPrime[i] = 1;
  // find all odd non-primes
  #pragma omp parallel for schedule(dynamic)
  for (int i = 3; i <= lastNumberSqrt; i += 2)
    if (isPrime[i/2])
      for (int j = i*i; j <= lastNumber; j += 2*i)
        isPrime[j/2] = 0;
  // sieve is complete, count primes
  int found = lastNumber >= 2 ? 1 : 0;
  #pragma omp parallel for reduction(+:found)
  for (int i = 1; i <= memorySize; i++)
    found += isPrime[i];
  delete[] isPrime;
  return found;
}
like image 169
silverjam Avatar answered Nov 15 '22 02:11

silverjam