实际上,我使用的是一个多线程程序,它涉及很多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
?这些模块中的变量范围是什么?
这看起来像threadsave模块,但存在错误:
这是一个更好的版本:
因为:
以上语法适用于Python2.3及更低版本
下面是一个改进版本,它的功能完全相同:
是的,你的模块是threadsave。 可以添加一些内容来防止用户以非线程方式使用它:
但仍然无法知道字符串将以何种顺序写入文件。你知道吗
相关问题 更多 >
编程相关推荐