簡體   English   中英

Python:線程

[英]Python: threading

我想多次啟動線程,但前提是它沒有運行。 我正在嘗試一個簡單的模型:

import threading 
import time


def up (x, r):
    time.sleep(3)
    r['h'] = x + 1


hum = {'h' : 0}

while True:
    print(hum['h'])
    H = threading.Thread(target = up, args=(hum['h'],hum))
    H.daemon=True
    if not H.isAlive():
        H.start()
    print(threading.active_count())

另外我不明白的是:當我運行程序時,它打印:0。然后在 3 秒后打印:1 等等,每 3 秒增加 1。但我認為它會打印:0。然后3 秒后它會打印: 1. 然后立即快速增加。 因為在啟動第一個線程后,它會立即啟動下一個,依此類推。 為什么會這樣? 如果線程已經在運行,如何不啟動它?

您的代碼中會發生什么:

  • 打印hum['h']
  • 創建一個線程(注意你創建了它,你還沒有開始它)
  • 設置屬性值
  • 如果線程未啟動,則啟動它
  • 打印活動線程的數量(活動,未啟動

由於您每次都替換H變量,因此每次立即啟動時都會有一個新線程。

如果您在 if for the is alive 中添加一個顯示“開始”的打印,您將看到它每次都被調用。

您可以使用join()等待線程完成:

import threading 
import time


def up (x, r):
    time.sleep(3)
    r['h'] = x + 1


hum = {'h' : 0}

while True:
    print(hum['h'])
    H = threading.Thread(target = up, args=(hum['h'],hum))
    H.daemon=True
    H.start()
    H.join()
    print(threading.active_count())

如果您不想等待,您可以將當前正在運行的線程保存在一個變量中並在循環中檢查它:

import threading 
import time


def up (x, r):
    time.sleep(3)
    r['h'] = x + 1


hum = {'h' : 0}

current_thread = None

while True:
    print(hum['h'])
    if current_thread is None:
        current_thread = threading.Thread(target = up, args=(hum['h'],hum))
        current_thread.daemon=True
        current_thread.start()
    elif not current_thread.isAlive():
        current_thread = threading.Thread(target = up, args=(hum['h'],hum))
        current_thread.daemon=True
        current_thread.start()

不確定我是否完全理解了你的問題,但這里有一些想法。 當我運行你的代碼時,我得到越來越多的活動線程,因為你每次都在創建一個新線程,檢查它的狀態(它總是not alive )然后啟動它。 你想要做的是檢查最后一個運行線程的狀態,如果它不活躍,則開始一個新線程。 為此,如果舊線程完成,您應該創建一個新線程:

def up (x, r):
    time.sleep(3)
    r['h'] = x + 1


def main():
    hum = {'h' : 0}
    H = threading.Thread(target = up, args=(hum['h'],hum))
    H.daemon=True

    while True:
        # print(hum['h'])
        if not H.isAlive():
            H = threading.Thread(target = up, args=(hum['h'],hum))
            H.daemon=True
            H.start()
            print(threading.active_count())

暫無
暫無

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

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