【python】多进程锁multiprocess.Lock

2013-09-13 13:48 11613人阅读 评论(2) 收藏 举报
【python】多进程锁multiprocess.Lock 分类:
Python(38) 【python】多进程锁multiprocess.Lock

同步的方法基本与多线程相同。

1) Lock

当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突。

  1. import multiprocessing
  2. import sys
  3. def worker_with(lock, f):
  4. with lock:
  5. fs = open(f,"a+")
  6. fs.write('Lock acquired via with\n')
  7. fs.close()
  8. def worker_no_with(lock, f):
  9. lock.acquire()
  10. try:
  11. fs = open(f,"a+")
  12. fs.write('Lock acquired directly\n')
  13. fs.close()
  14. finally:
  15. lock.release()
  16. if __name__ == "__main__":
  17. f = "file.txt"
  18. lock = multiprocessing.Lock()
  19. w = multiprocessing.Process(target=worker_with, args=(lock, f))
  20. nw = multiprocessing.Process(target=worker_no_with, args=(lock, f))
  21. w.start()
  22. nw.start()
  23. w.join()
  24. nw.join()
 
在上面的例子中,如果两个进程没有使用lock来同步,则他们对同一个文件的写操作可能会出现混乱。

2)Semaphore

Semaphore用来控制对共享资源的访问数量,例如池的最大连接数。

  1. import multiprocessing
  2. import time
  3. def worker(s,i):
  4. s.acquire()
  5. print(multiprocessing.current_process().name + " acquire")
  6. time.sleep(i)
  7. print(multiprocessing.current_process().name + " release")
  8. s.release()
  9. if __name__ == "__main__":
  10. s = multiprocessing.Semaphore(2)
  11. for i in range(5):
  12. p = multiprocessing.Process(target=worker, args=(s,i*2))
  13. p.start()

上面的实例中使用semaphore限制了最多有2个进程同时执行。

3)Event

Event用来实现进程间同步通信。

  1. import multiprocessing
  2. import time
  3. def wait_for_event(e):
  4. """Wait for the event to be set before doing anything"""
  5. print ('wait_for_event: starting')
  6. e.wait()
  7. print ('wait_for_event: e.is_set()->' + str(e.is_set()))
  8. def wait_for_event_timeout(e, t):
  9. """Wait t seconds and then timeout"""
  10. print ('wait_for_event_timeout: starting')
  11. e.wait(t)
  12. print ('wait_for_event_timeout: e.is_set()->' + str(e.is_set()))
  13. if __name__ == '__main__':
  14. e = multiprocessing.Event()
  15. w1 = multiprocessing.Process(name='block',
  16. target=wait_for_event,
  17. args=(e,))
  18. w1.start()
  19. w2 = multiprocessing.Process(name='non-block',
  20. target=wait_for_event_timeout,
  21. args=(e, 2))
  22. w2.start()
  23. time.sleep(3)
  24. e.set()
  25. print ('main: event is set')

#the output is:
#wait_for_event_timeout: starting
#wait_for_event: starting
#wait_for_event_timeout: e.is_set()->False
#main: event is set
#wait_for_event: e.is_set()->True

 
 
上一篇:python multiprocessing多进程应用


下一篇:Bootstrap 引用的标准模板