Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #ifdef _OPENMP
00033 # include <omp.h>
00034 #endif
00035
00036 #include <System/cmtkThreads.h>
00037 #include <System/cmtkConsole.h>
00038
00039 template<class TParam>
00040 void
00041 cmtk::ThreadPool::Run
00042 ( const TaskFunction taskFunction, std::vector<TParam>& taskParameters, const size_t numberOfTasksOverride )
00043 {
00044 if ( ! this->m_ThreadsRunning )
00045 {
00046 this->StartThreads();
00047 }
00048
00049 const size_t numberOfTasks = numberOfTasksOverride ? numberOfTasksOverride : taskParameters.size();
00050 if ( ! numberOfTasks )
00051 {
00052 StdErr << "ERROR: trying to run zero tasks on thread pool. Did you forget to resize the parameter vector?\n";
00053 exit( 1 );
00054 }
00055
00056 #ifdef _OPENMP
00057
00058 const int nThreadsOMP = std::max<int>( 1, 1+Threads::GetNumberOfThreads() - std::min<int>( numberOfTasks, this->m_NumberOfThreads ) );
00059 omp_set_num_threads( nThreadsOMP );
00060 #endif
00061
00062 #ifdef CMTK_BUILD_SMP
00063
00064 this->m_TaskFunction = taskFunction;
00065
00066
00067 this->m_NumberOfTasks = numberOfTasks;
00068 this->m_TaskParameters.resize( this->m_NumberOfTasks );
00069 this->m_NextTaskIndex = 0;
00070
00071
00072 for ( size_t idx = 0; idx < numberOfTasks; ++idx )
00073 {
00074 this->m_TaskParameters[idx] = &(taskParameters[idx]);
00075 }
00076 this->m_TaskWaitingSemaphore.Post( numberOfTasks );
00077
00078
00079 for ( size_t idx = 0; idx < numberOfTasks; ++idx )
00080 {
00081 this->m_ThreadWaitingSemaphore.Wait();
00082 }
00083 #else
00084
00085 for ( size_t idx = 0; idx < numberOfTasks; ++idx )
00086 {
00087 taskFunction( &taskParameters[idx], idx, numberOfTasks, 0, 1 );
00088 }
00089 #endif
00090
00091 #ifdef _OPENMP
00092
00093 omp_set_num_threads( Threads::GetNumberOfThreads() );
00094 #endif
00095 }