title: How to use SyncManager.Lock or Event correctly?
body: <p>I'm having trouble using <code>SyncManager.Lock</code> correctly. I read the <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.managers.SyncManager.Lock" rel="nofollow noreferrer">official doc</a>, but it offers no working example. I also have no idea how to use <code>SyncManager.Event</code> correctly.</p>
  
  <p>Below is the minimal code to illustrate my problem. <code>client1</code> and <code>client2</code> both need to update a shared object <code>Struct</code>. However, I want <code>client1</code> to acquire the lock first, update <code>Struct</code>, and then pass control to <code>client2</code>. If you run the code below as-is, the <code>print</code> statements are all mixed up.</p>
  
  <pre><code>import multiprocessing as mp
  from multiprocessing.managers import SyncManager
  import time
  
  class Struct:
      def __init__(self):
          self.a = []
  
      def update(self, x, y):
          self.a.append(x ** 2)
  
      def get(self):
          return self.a
  
  class Server(SyncManager):
      pass
  
  global_S = Struct()
  Server.register('Struct', lambda: global_S)
  
  def server_run():
      print('Server starting ...')
      manager = Server(('localhost', 8080), authkey=b'none')
      manager.get_server().serve_forever()
  
  
  def client_run(name, x, y, wait):
      server_proc = Server(('localhost', 8080), authkey=b'none')
      server_proc.connect()
      S = server_proc.Struct()
      with server_proc.Lock():
          for i in range(5):
              S.update(x+i, y+i)
              print(name, S.get())
              time.sleep(wait)
  
  
  server = mp.Process(target=server_run)
  server.daemon = True
  
  client1 = mp.Process(target=client_run, args=('c1', 3,7, 1))
  client2 = mp.Process(target=client_run, args=('c2', 100,120, .6))
  
  server.start()
  time.sleep(0.3) # wait for server to spawn up
  client1.start()
  time.sleep(0.3)
  client2.start()
  
  client1.join()
  client2.join()
  </code></pre>
  
  <p>Sample output:</p>
  
  <pre><code>Server starting ...
  c1 [9]
  c2 [9, 10000]
  c2 [9, 10000, 10201]
  c1 [9, 10000, 10201, 16]
  c2 [9, 10000, 10201, 16, 10404]
  c1 [9, 10000, 10201, 16, 10404, 25]
  c2 [9, 10000, 10201, 16, 10404, 25, 10609]
  c2 [9, 10000, 10201, 16, 10404, 25, 10609, 10816]
  c1 [9, 10000, 10201, 16, 10404, 25, 10609, 10816, 36]
  c1 [9, 10000, 10201, 16, 10404, 25, 10609, 10816, 36, 49]
  </code></pre>