我有线程代码,每个线程需要写入同一个文件.为了防止并发问题,我使用的是Lock对象.
我的问题是我是否正确使用了锁.如果我从每个线程中设置锁定,该锁定是全局的还是仅特定于该特定线程?
基本上,我应该先创建一个Lock并将其引用传递给每个线程,还是可以像在此处一样在线程内设置它:
import time
from threading import Thread,Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self,thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt','a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
最佳答案
在方法外创建锁.
原文链接:https://www.f2er.com/python/439365.htmlclass Agent(Thread):
mylock = Lock()
def write_result(self):
self.mylock.acquire()
try:
...
finally:
self.mylock.release()
或者如果使用python> = 2.5:
class Agent(Thread):
mylock = Lock()
def write_result(self):
with self.mylock:
...
要在python 2.5中使用它,您必须从以后导入语句:
from __future__ import with_statement