python – 多线程资源访问 – 我在哪里放锁?

前端之家收集整理的这篇文章主要介绍了python – 多线程资源访问 – 我在哪里放锁?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有线程代码,每个线程需要写入同一个文件.为了防止并发问题,我使用的是Lock对象.

我的问题是我是否正确使用了锁.如果我从每个线程中设置锁定,该锁定是全局的还是仅特定于该特定线程?

基本上,我应该先创建一个Lock并将其引用传递给每个线程,还是可以像在此处一样在线程内设置它:

  1. import time
  2. from threading import Thread,Lock
  3. def main():
  4. for i in range(20):
  5. agent = Agent(i)
  6. agent.start()
  7. class Agent(Thread):
  8. def __init__(self,thread_num):
  9. Thread.__init__(self)
  10. self.thread_num = thread_num
  11. def run(self):
  12. while True:
  13. print 'hello from thread %s' % self.thread_num
  14. self.write_result()
  15. def write_result(self):
  16. lock = Lock()
  17. lock.acquire()
  18. try:
  19. f = open('foo.txt','a')
  20. f.write('hello from thread %s\n' % self.thread_num)
  21. f.flush()
  22. f.close()
  23. finally:
  24. lock.release()
  25. if __name__ == '__main__':
  26. main()
最佳答案
方法外创建锁.

  1. class Agent(Thread):
  2. mylock = Lock()
  3. def write_result(self):
  4. self.mylock.acquire()
  5. try:
  6. ...
  7. finally:
  8. self.mylock.release()

或者如果使用python> = 2.5:

  1. class Agent(Thread):
  2. mylock = Lock()
  3. def write_result(self):
  4. with self.mylock:
  5. ...

要在python 2.5中使用它,您必须从以后导入语句:

  1. from __future__ import with_statement

猜你在找的Python相关文章