我有一个多线程的代码,每个线程都需要写入同一个文件。为了避免并发问题,我正在使用Lock对象。
我的问题是,我是否正确地使用了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()