我有线程代码,其中每个线程需要写入相同的文件。为了防止并发问题,我使用了一个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()
是的,你把它移到了方法之外,但你仍然在线程本身中创建它。这不是一个问题吗? – 2009-01-15 19:31:23
@cgoldberd:它被创建为* class *属性,这意味着将为所有线程创建一个单独的属性。这是一个更好的地方,因为一切都停留在线程类上。陷入困境的是 – nosklo 2009-01-15 19:34:38
。我喜欢那种方式 – 2009-01-15 19:37:32