title: How to synchronize between multiple async processes in Python?
body: <p>I have an async http webs service using fastapi. I am running multiple instances of the same service on the server on a different port and I have an nginx server in front so I can utilise them all. I have a particular resource I need to protect that only one client is accessing it.</p>
  <pre><code>@app.get(&quot;/do_something&quot;)
  async def do_something():
       critical_section_here()
  </code></pre>
  <p>I tried to protect this critical section using a file lock like this:</p>
  <pre><code>@app.get(&quot;/do_something&quot;)
  async def do_something():
      with FileLock(&quot;dosomething.lock&quot;):
          critical_section()
  </code></pre>
  <p>This will prevent multiple processes to enter the critical section at the same time. But what I found is that this will actually dead lock. Think about the following event:</p>
  <ol>
  <li>client 1 connected to port 8000 and enter the critical section</li>
  <li>while client 1  is still using the resource client 2 is routed to the same port 8000 and then it will try to acquire the file lock, it cannot, so it will keep trying and this will block the execution of client 1 and client 1 will never be able to release the filelock and this means not only this process is locked every other server instance will be locked as well.</li>
  </ol>
  <p>Is there a way for me to coordinate these processes so that only one of them access the critical section? I thought about adding a timeout to the filelock but I really don't want to reject user, I just want to wait until it's his/her turn to enter the critical section.</p>