我实际上正在使用一个涉及大量 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
?这些模块中变量的范围是什么?