[Insight-users] Thread safety of itk (e.g. itk::MersenneTwisterRandomVariateGenerator)

Floca, Ralf Ralf.Floca at med.uni-heidelberg.de
Wed Apr 11 07:14:06 EDT 2007


Hello

I have a question concerning thread safety of itk components. At least
one seems not to be thread safe. If using
itk::MersenneTwisterRandomVariateGenerator in multiple threads of an
application it may crash. As far as I can assess the cause is the fact
that there is only a single instance of
itk::MersenneTwisterRandomVariateGenerator (the static member
itk::MersenneTwisterRandomVariateGenerator::m_Instance). Now it can
happen that multiple threads call
itk::MersenneTwisterRandomVariateGenerator::GetIntegerVariate() and more
then one thread passes the first statement
(itkMersenneTwisterRandomVariateGenerator.h, line 404, see below) before
any thread executes the following line (line 405). If this happens it is
possible that the index "left" drops below 0. Therefore the
MersenneTwister would never be reloaded and "pNext" is iterating through
memory not belonging to the array "state" anymore.

Section of itkMersenneTwisterRandomVariateGenerator.h:
401  inline MersenneTwisterRandomVariateGenerator::IntegerType 
402   MersenneTwisterRandomVariateGenerator::GetIntegerVariate()
403    {
404    if( left == 0 ) reload();
405    --left;
406
407    register IntegerType s1;
408    s1 = *pNext++;
409    s1 ^= (s1 >> 11);
410    s1 ^= (s1 <<  7) & 0x9d2c5680UL;
411    s1 ^= (s1 << 15) & 0xefc60000UL;
412    return ( s1 ^ (s1 >> 18) );
413    }

Every itk component using the mersenne twister is therfore error-prone
in multi threading environments. In my case the application crashes when
I use more then one thread for calculations and both threads are using
an itk::ImageRandomConstIteratorWithIndex (which uses the mersenne
twister).

Would it be sensible solution to us an itk::MutexLock or
itk::SimpleMutexLock to safeguard
MersenneTwisterRandomVariateGenerator::GetIntegerVariate() (and other
methods that need to). Or is there any reasoning against it?

Further are there any other components in itk that might be prone to
such an error? So that I can be aware of that in my multi threading test
cases.

Thanks.

Regards,
Ralf o Floca

---------------------------------------------------------------------
Ralf Floca
Department of Medical Informatics
University of Heidelberg                           
Im Neuenheimer Feld 400            
D-69120 Heidelberg, Germany               
Phone: +49 (0)6221 56-7484
Fax:                 -4997  
http://www.klinikum.uni-heidelberg.de/mi 
ralf.floca at med.uni-heidelberg.de
---------------------------------------------------------------------


More information about the Insight-users mailing list