ENH: New set_default_num_threads function, and ThreadScope class

This MR adds two new features to the threading module:

  • A new NoOfThreads::set_default_num_threads function, intended to be called from application main() routines, for applications which allow the user to set the number of threads from the command-line. This function will set the default number of threads used by NoOfThreads instance, and hence the parfor/apply functions. If this function is never called, the default number of threads is dictated by the FSL_NUM_THREADS environment variable, or defaults to 1 (single-threaded) if that variable is not set. These changes have only involved changes to static fields of the NoOfThreads class, and so should preserve ABI compatibility with the last release (however new projects will need to be re-compiled against this new vesrion to advantage of the new feature).

  • A new ThreadScope class which allows the default number of threads used by NoOfThreads/parfor/apply to be temporarily changed in a local scope. This can be used by applications to temporarily disable/adjust parallelism - for example, if a routine is being run in parallel, it can use a ThreadScope to ensure that no nested paralellism takes place. The ThreadScope class is intended to be used like so:

    // Input values
    std::vector<int> values = {1, 2, 3, 4, 5};
    
    // Function which performs a
    // calculation on one value
    auto do_calc = [&](int i) {
    
      // Ensure that calls within this scope
      // only use one thread.
      ThreadScope ts(1);
    
      // Call functions which may otherwise
      // have parallelised their work
      ...
    };
    
    // Call do_calc on each value in parallel
    Utilities::parfor(do_calc, values.begin(), values.end());

This MR also contains a bug fix to the parfor and apply functions which was causing compilation failure on attempts to pass more than one input iterator of a different type.

Edited by Paul McCarthy

Merge request reports

Loading