[Insight-users] thread-safe containers

Miller, James V (Research) millerjv at crd.ge.com
Wed Jan 19 09:25:44 EST 2005


Benjamin,

Another approach without mutexes:

Add an ivar to the class keeps an std::vector<> for each thread.
Essentially,
this is an std::vector<std::vector<> >.  Each thread, therefore, can append
its information to a different vector.  In the BeforeThreadedGenerateData()
method, you can setup up this ivar (clear any previous information), and 
in the AfterThreadedGenerateData() method, you can consolidate the list 
from list thread.  BeforeThreadedGenerateData() and
AfterThreadedGenerateData()
run single threaded. The important thing to do in
BeforeThreadedGenerateData() is allocate the "outer" vector so that there is
one "inner" vector available
for each thread.  Then in the ThreadedGenerateData() method, you append 
information to the appropriate inner vector, i.e. 

	m_ThreadVectors[threadID].push_back( foo );

We do this type of thing frequently to cache information from separate
threads.
StatisticsImageFilter does this to cache the sum, sum of squares, and pixel
count for each thread. Then the AfterThreadedGenerateData() pulls all this 
information together to calculate the image mean, standard deviation, etc.

The benefit of this approach is that an mutex is not needed.  Mutexes can 
be very expensive.

Jim



-----Original Message-----
From: Benjamin King [mailto:king.benjamin at mh-hannover.de]
Sent: Wednesday, January 19, 2005 8:39 AM
To: ITK
Subject: Re: [Insight-users] thread-safe containers


Hello,

I found out myself:

> Can anyone tell me, if different threads can safely append to a
> std::vector<T> and what I can do about it if they can't?
They can't, but I now use itk::SimpleMutexLock to protect container access.

cheers,
 Benjamin

-- 
Benjamin King
Institut fur Medizinische Informatik
Medizinische Hochschule Hannover
Tel.: +49  511  532-2663
_______________________________________________
Insight-users mailing list
Insight-users at itk.org
http://www.itk.org/mailman/listinfo/insight-users


More information about the Insight-users mailing list