这是一个线程安全的模块,实际上你是怎么写的?

2024-06-28 16:18:30 发布

您现在位置:Python中文网/ 问答频道 /正文

实际上,我使用的是一个多线程程序,它涉及很多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?这些模块中的变量范围是什么?


Tags: 模块thepyimportlocktargetdefthread
1条回答
网友
1楼 · 发布于 2024-06-28 16:18:30

这看起来像threadsave模块,但存在错误:

这是一个更好的版本:

def RealAppending(the_str):
    lock.acquire()
    try:
        the_file = open("test.txt", "a")
        try:
            the_file.write(the_str) # write
        finally:
            the_file.close()
    finally: # if an error occurs
        lock.release()

因为:

  • 如果写入文件时发生错误,则必须释放锁

以上语法适用于Python2.3及更低版本

下面是一个改进版本,它的功能完全相同:

def RealAppending(the_str):
    with lock:
        with open("test.txt", "a") as the_file:
            the_file.write(the_str) # write

是的,你的模块是threadsave。 可以添加一些内容来防止用户以非线程方式使用它:

# write.py
__all__ = ['AppendStr'] # put all functions in except the ones others shall not see
# so id you do from write import * nothing else will be imported but what is __all__

但仍然无法知道字符串将以何种顺序写入文件。你知道吗

相关问题 更多 >