Hello!

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.

Edited 6 Years Ago by Godflesh: n/a

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

@contextmanager
def acquired(condition):
    condition.acquire()
    try:
        yield condition
    finally:
        condition.release()

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")
            f_out.write(some_data)
            f_out.close()

class B(object):
    def get_data(self):
        with acquired(my_condition):
            f_in = open(filename)
            data = f_in.read()
            f_in.close()
        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.

Edited 6 Years Ago by Gribouillis: n/a

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