Table of Contents Previous Next
Logo
Developing a File System Server in Python : 25.3 Thread Safety
Copyright © 2003-2009 ZeroC, Inc.

25.3 Thread Safety

The server code we developed in Section 25.2 is not quite correct as it stands: if two clients access the same file in parallel, each via a different thread, one thread may read the _lines data member while another thread updates it. Obviously, if that happens, we may write or return garbage or, worse, crash the server. However, we can make the read and write operations thread-safe with a few trivial changes to the FileI class:
    def __init__(self, name, parent):
        self._name = name
        self._parent = parent
        self._lines = []
        self._mutex = threading.Lock()

        # ...

    def name(self, current=None):
        return self._name

    def read(self, current=None):
        self._mutex.acquire()
        lines = self._lines[:] # Copy the list
        self._mutex.release()
        return lines

    def write(self, text, current=None):
        self._mutex.acquire()
        self._lines = text
        self._mutex.release()
We modified the constructor to add the instance member _mutex, and then enclosed our read and write implementations in a critical section. (The name method does not require a critical section because the file’s name is immutable.)
No changes for thread safety are necessary in the DirectoryI class because the Directory interface, in its current form, defines no operations that modify the object.
Table of Contents Previous Next
Logo