# Multithread filter how to write to the same buffer

**URL:** https://discourse.itk.org/t/multithread-filter-how-to-write-to-the-same-buffer/1029
**Category:** Beginner Questions
**Created:** [June 24, 2018, 6:24pm UTC](https://discourse.itk.org/t/multithread-filter-how-to-write-to-the-same-buffer/1029 "2018-06-24T18:24:22Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![blowekamp](https://discourse.itk.org/user_avatar/discourse.itk.org/blowekamp/32/79_2.png) [@blowekamp](https://discourse.itk.org/u/blowekamp)
#### Post date: [June 25, 2018, 5:27pm UTC](https://discourse.itk.org/t/multithread-filter-how-to-write-to-the-same-buffer/1029/4 "2018-06-25T17:27:58Z")

</div>

You are find a patch which adds a lock here:

> <https://github.com/InsightSoftwareConsortium/ITK/commit/df71cb261369315233b194dd5a45aa940de7ef26#diff-b653c76bdf33fe79e2b609767482b850>
>
> Coarsely fix threading issue with IsoContourDistanceImageFilter,
> utilized by the… ApproximateSignedDistance, and NarrowBand LevelSet
> framework. This patch address a periodic failing test on the ITK
> dashboard: itkApproximateSignedDistanceMapImageFilterTest1. And likely
> address NarrowBand predictability issues previously encountered.
> 
> This patch oafishly utilizes a mutex lock when reading and writing to
> the output image. Given, that this filter only updates the values
> around the iso-contour the locking does not occur for every pixel.
> 
> The algorithm should be re-witten with out the concurrent read/write
> problems. Potential solutions include, having each thread allocate a separate
> output buffer, then merging. Another is to crop the regions and handle
> the overlapping boundaries separately. But this would heavily depend
> on how the output regions are split, and there is a trend to have less
> control over the splitting methods.

And another similar discussion to this type of issue here:

> [@threadId in ParallelizeImageRegion](https://discourse.itk.org/t/threadid-in-parallelizeimageregion/1008/7):
>
> There are two components to be aware of: [SimpleFastMutexLock](https://itk.org/Doxygen/html/classitk_1_1SimpleFastMutexLock.html)[MutexLockHolder](https://itk.org/Doxygen/html/classitk_1_1MutexLockHolder.html) The mutex is variable scoped to provide serialized access. For your case, the need is to control access to threads in an instance of the class. So you are looking at a lock with object scope, a member variable. The holder provides exception safe lock/unlock handling of the mutex via [RAII](https://en.cppreference.com/w/cpp/language/raii). Here is an example which controls initialization and access to a global variable: [https://github.com/InsightSoftwareConsortium/…](https://github.com/InsightSoftwareConsortium/ITK/blob/master/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx#L62-L72)

---

_[View the full topic](https://discourse.itk.org/t/multithread-filter-how-to-write-to-the-same-buffer/1029)._
