Search code examples
c++concurrencyparallel-processingfactorial

Concurrency::combinable / c++


this is code that computes factorial of an arbitrary number:

unsigned long long factorial(int n)
{
  Concurrency::combinable<unsigned long long> products=Concurrency::combinable<unsigned long long>([]()->unsigned long long{return 1LL;});
  Concurrency::parallel_for(1, n+1, [&products](int i){products.local() *= i;});
  return products.combine([](unsigned long long lProduct, unsigned long long rProduct){ return lProduct*rProduct;  });
}

can u please explain to me:

    • what does ()-> mean? i think () is a functor, but of which class? and why is there ->?
    • what is 1LL?

Solution

  • ->unsigned long long declares the return type of the lambda function.

    You can google on C++ lambda for more information, but be basic syntax is something like:

    [capture_mode] (formal_parameters) mutable -> return_type {body}
    

    1LL is basically the same as static_cast<long long>(1). 1 is an int, 1LL is a long long.

    However, a shorter way to write it would have been:

    Concurrency::combinable([]{return 1ULL;});
    

    Where the types should be automatically deduced. Note that I used ULL instead of LL to make it an unsigned long long, as in the original code.