file write collision consideration
MRAB
google at mrabarnett.plus.com
Tue Jan 20 11:10:21 EST 2009
RGK wrote:
> I have a thread that is off reading things some of which will get
> written into a file while another UI thread manages input from a user.
>
> The reader-thread and the UI-thread will both want to write stuff to the
> same output file. What first comes to mind is that there may be write
> collisions, ie both trying to write at the same time.
>
> Should I do something like:
>
>
> if busyFlag:
> while busyFlag:
> sleep(10)
> else:
> busyFlag = True
> {write stuff to file}
> busyFlag = False
>
>
> in both threads? Is there some other approach that would be more
> appropriate?
>
> Thanks in advance for your advice
>
If you're using the threading module, I suggest you look at the
threading.RLock class:
my_lock = threading.RLock()
...
with my_lock:
{write stuff to file}
or, if you're using an older version of Python:
my_lock = threading.RLock()
...
my_lock.acquire()
{write stuff to file}
my_lock.release()
More information about the Python-list
mailing list