Multithreading

From user's Wiki!
Jump to: navigation, search

This page provides you some strategies on how to parallelize your code

ITK

Override the method ThreadedGenerateData:

template< class T >
void ApplyMaskImageFilter< T >::ThreadedGenerateData(
  const typename itk::ImageSource<T>::OutputImageRegionType& outputRegionForThread,
  int threadId )

And iterate over the outputRegionForThread:

typename T::Pointer outputImage = this->GetOutput();
itk::ImageRegionIterator<T> itOut( outputImage, outputRegionForThread );
for (itOut.GoToBegin(); !itOut.IsAtEnd(); itOut++)
{
    itOut.Set(something);
}

See also:

OpenMP

OpenMP is a platform-independent API that facilitates multithreading on shared memory architectures. It is integrated into many modern compilers and makes it especially easy to parallelize loops without the need to explicitly manage threads and the communication between them.

Add the following line to the csn file:

# Activate OpenMP support of the GNU compilers (gcc, g++)
myProject.AddDefinitions(["-fopenmp"], _NOT_WIN32 = 1)

# Link your application/library explicitly against GCC's OpenMP implementation (gomp)
myProject.AddLibraries(["gomp"], _NOT_WIN32 = 1)

# Activate OpenMP in Visual Studio
myProject.AddDefinitions(["/openmp"], _WIN32 = 1)

Use openMP in an interation loop:

#pragma omp parallel for
for(int z = 0; z < height*width; z++) 
{ 
    pDest[z] = (pSrc[z*4+0]*3735 + pSrc[z*4 + 1]*19234+ pSrc[z*4+ 2]*9797)>>15; 
}

See also:

Boost

Include this file:

#include <boost/thread.hpp>

Create a workker thread class with member function operator()():

class WorkerThread
{
public:
	WorkerThread( )
	{
	}

	void operator()()
	{
		//Thread execution function
	}

Create several worker threads instances and run them simultaneously:

boost::thread_group threads;
for( size_t iThread = 0; iThread < 4; ++iThread )
{
	WorkerThread workerThread( );

	threads.create_thread(workerThread);
}
threads.join_all();

See also: