@@ -49,6 +49,7 @@ working directory is currently used. To do so, create a :class:`FileLock <filelo
4949
5050.. code-block :: python
5151
52+ import os
5253 from filelock import Timeout, FileLock
5354
5455 file_path = " high_ground.txt"
@@ -62,16 +63,19 @@ locks:
6263.. code-block :: python
6364
6465 with lock:
65- with open (file_path, " a" ) as f:
66- f.write(" Hello there!" )
66+ if not os.path.exists(file_path):
67+ with open (file_path, " w" ) as f:
68+ f.write(" Hello there!" )
69+ # here, all processes can see consistent content in the file
6770
6871 lock.acquire()
6972 try :
70- with open (file_path, " a" ) as f:
71- f.write(" General Kenobi!" )
73+ if not os.path.exists(file_path):
74+ with open (file_path, " w" ) as f:
75+ f.write(" General Kenobi!" )
7276 finally :
7377 lock.release()
74-
78+ # here, all processes can see consistent content in the file
7579
7680 @lock
7781 def decorated ():
@@ -80,6 +84,11 @@ locks:
8084
8185 decorated()
8286
87+ Note: When a process gets the lock (i.e. within the `with lock: ` region), it is usually good to check what has
88+ already been done by other processes. For example, each process above first check the existence of the file. If
89+ it is already created, we should not destroy the work of other processes. This is typically the case when we want
90+ just one process to write content into a file, and let every process to read the content.
91+
8392The :meth: `acquire <filelock.BaseFileLock.acquire> ` method accepts also a ``timeout `` parameter. If the lock cannot be
8493acquired within ``timeout `` seconds, a :class: `Timeout <filelock.Timeout> ` exception is raised:
8594
0 commit comments