Start New Discussion within our Software Development Community


I have more questions :)

Is it possibe to create a "threadlock", "lock" if you use a file as a common resource?

If you have a class that create data and put the data into a file and you have another class that will take data from the same file.

How do you stop them from using the file at the same time? Each class use its own thread.

If its possible, please give me an code example.

You can use a threading.Condition object. I usually use this in a 'with' context like this

#from __future__ import with_statement # uncomment if python 2.5
from contextlib import contextmanager
from threading import Condition

def acquired(condition):
        yield condition

my_condition = Condition()
filename = "my_file.txt"

class A(object):
    def put_data(self, some_data):
        with acquired(my_condition):
            f_out = open(filename, "w")

class B(object):
    def get_data(self):
        with acquired(my_condition):
            f_in = open(filename)
            data =
        return data

You can also use the same technique to work with a file kept open for both reading and writing. The amount of work done when the condition is acquired should be kept as small as possible because the condition.acquire() statement blocks a thread until the condition object is available.

This question has already been answered. Start a new discussion instead.