Set the Default Number of Threads#

Synopsis#

Set the default number of threads for multi-threading.

The default number of threads can also be set via the environment variable, ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS.

Results#

Filter's default number of threads: 3

Code#

C++#

#include "itkMultiThreaderBase.h"
#include "itkMedianImageFilter.h"

int
main(int argc, char * argv[])
{
  if (argc != 2)
  {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0];
    std::cerr << " <NumberOfThreads>";
    std::cerr << std::endl;
    return EXIT_FAILURE;
  }

  const auto numberOfThreads = static_cast<unsigned int>(std::atoi(argv[1]));

  itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(numberOfThreads);

  constexpr unsigned int Dimension = 2;
  using PixelType = float;
  using ImageType = itk::Image<PixelType, Dimension>;
  using FilterType = itk::MedianImageFilter<ImageType, ImageType>;
  auto filter = FilterType::New();

  const auto filterDefaultThreads = filter->GetMultiThreader()->GetGlobalDefaultNumberOfThreads();
  std::cout << "Filter's default number of threads: " << filterDefaultThreads << std::endl;

  if (filterDefaultThreads != numberOfThreads)
  {
    std::cerr << "Filter does not have expected default number of threads." << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Python#

#!/usr/bin/env python
import itk

parser = argparse.ArgumentParser(description="Set the Default Number Of Threads.")
parser.add_argument("number_of_threads", type=int)
args = parser.parse_args()

# Create a MultiThreaderBase instance to get access to its static methods
threader = itk.MultiThreaderBase.New()
threader.SetGlobalDefaultNumberOfThreads(args.number_of_threads)

filt = itk.MedianImageFilter.New()
filter_default_threads = filt.GetMultiThreader().GetGlobalDefaultNumberOfThreads()

print("Filter's default number of threads: {}".format(filter_default_threads))

assert filter_default_threads == args.number_of_threads

Classes demonstrated#

class MultiThreaderBase : public itk::Object

A class for performing multithreaded execution.

Multithreaders are a class hierarchy that provides support for multithreaded execution by abstracting away platform-specific details. This class can be used to execute a single method on multiple threads or to parallelize an operation over a given image region or array.

Subclassed by itk::PoolMultiThreader, itk::TBBMultiThreader

See itk::MultiThreaderBase for additional documentation.