# Multiprocessing for write and read file

**URL:** https://discourse.itk.org/t/multiprocessing-for-write-and-read-file/2395
**Category:** Engineering
**Tags:** multiprocessing
**Created:** [November 12, 2019, 1:18am UTC](https://discourse.itk.org/t/multiprocessing-for-write-and-read-file/2395 "2019-11-12T01:18:12Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![zhuangming.shen](https://discourse.itk.org/letter_avatar_proxy/v4/letter/z/4af34b/32.png) [@zhuangming.shen](https://discourse.itk.org/u/zhuangming.shen)
#### Post date: [November 12, 2019, 1:18am UTC](https://discourse.itk.org/t/multiprocessing-for-write-and-read-file/2395/1 "2019-11-12T01:18:12Z")

</div>

Hi all,

I’m programming a python based software which uses multiprocessing technique. For one process, it will call “itk.ImageFileWrite” to export a 3D volume to a NRRD file (“write” operation). For the rest processes, they will call “itk.ImageFileRead” to get voxel values from this NRRD file (“read” operation). My question is how to know whether the “write” operation has completed before a “read” operation, otherwise, “read” operation for some processes will fail because the NRRD file is still in writing in one process, although I think the time difference is less than 1 second. Any suggestion are welcome.

Regards,

Zhuangming Shen

---

<div class="post-metadata">

### Author: ![dzenanz](https://discourse.itk.org/user_avatar/discourse.itk.org/dzenanz/32/1093_2.png) [@dzenanz](https://discourse.itk.org/u/dzenanz)
#### Post date: [November 12, 2019, 2:50pm UTC](https://discourse.itk.org/t/multiprocessing-for-write-and-read-file/2395/2 "2019-11-12T14:50:20Z")

</div>

Protect the file using a `mutex` (possibly called a `lock` in Python). The writing thread acquires the lock before it starts writing, and releases it once it is finished. More in this [SO thread](https://stackoverflow.com/questions/16261902/python-any-way-to-get-one-process-to-have-a-write-lock-and-others-to-just-read).

---

<div class="post-metadata">

### Author: ![zhuangming.shen](https://discourse.itk.org/letter_avatar_proxy/v4/letter/z/4af34b/32.png) [@zhuangming.shen](https://discourse.itk.org/u/zhuangming.shen)
#### Post date: [November 13, 2019, 12:18am UTC](https://discourse.itk.org/t/multiprocessing-for-write-and-read-file/2395/3 "2019-11-13T00:18:28Z")

</div>

@dzenanz Thanks for your response.
