【发布时间】:2012-05-12 18:30:47
【问题描述】:
我实际上正在使用一个涉及大量 mysql 操作的多线程程序,基本上这很痛苦,因为你必须想出一个聪明的方法来使所有查询工作。这让我想到如何使模块线程安全。
无论如何,我试图以这种方式提出我的问题:假设您需要不断地将新内容附加到具有许多不同线程的 txt 文件中,main.py 肯定会如下工作:
import threading
lock = threading.RLock()
def AppendStr(the_str):
write_thread = threading.Thread(target = RealAppending, args = (the_str, ))
write_thread.start()
def RealAppending(the_str):
lock.acquire()
the_file = open("test.txt", "a")
the_file.append(the_str)
the_file.close()
lock.release()
def WorkerThread(some_arg):
do stuff
AppendStr("whatever you like")
for counter in range(100):
new_thread = threading.Thread(target = WorkerThread, args = (some_arg, ))
new_thread.start()
好吧,问题是,如果我想让代码整洁且更易于维护,如果我将下面的代码放入 write.py:
import threading
lock = threading.RLock()
def AppendStr(the_str):
write_thread = threading.Thread(target = RealAppending, args = (the_str, ))
write_thread.start()
def RealAppending(the_str):
lock.acquire()
the_file = open("test.txt", "a")
the_file.append(the_str)
the_file.close()
lock.release()
并在 main.py 中这样做:(我不太明白 import 在 python 中的工作原理)
import write
def WorkerThread(some_arg):
do stuff
write.AppendStr("whatever you like")
for counter in range(100):
new_thread = threading.Thread(target = WorkerThread, args = (some_arg, ))
new_thread.start()
如果有很多其他模块以多线程方式使用write.py,然后您将这些模块导入main.py 并从那里调用不同的def,该怎么办。一切都会按预期进行吗?如果没有,我应该怎么做才能设计一个可以像这样使用的终极线程安全模块?
如果你的write.py 被导入到许多其他模块中,它们是否都共享相同的lock?这些模块中变量的范围是什么?
【问题讨论】:
标签: python multithreading