簡體   English   中英

這是一個線程安全的模塊,實際上如何編寫一個模塊?

[英]Is this a thread-safe module, and actually how do you write one?

我實際上正在使用一個涉及許多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 ,該main.py 一切都會按預期進行嗎? 如果沒有,我應該如何設計一個最終的線程安全模塊,使其可以像這樣使用?

如果將write.py導入許多其他模塊中,它們是否共享相同的lock 這些模塊中變量的范圍是什么?

這看起來像一個threadave模塊,但是有錯誤:

這是一個更好的版本:

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()

因為:

  • 如果在寫入文件時發生錯誤,則必須釋放鎖

上面的語法適用於python 2.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__

但是,您仍然不知道字符串將以什么順序寫入文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM