簡體   English   中英

Python中的簡單線程示例

[英]Simple threads example in Python

我對Python中的線程有疑問(我承認,我是這個主題的新手)。

我有對象,我想在方法part1()(有一些隨機時間間隔)和part2()中生成數字列表 - 打印ASAP所有生成的數字。

這是我的代碼:

import random
import time
from threading import Thread


class GenerateRand:
    def __init__(self):
        self.h = []

    def part1(self):
        while True:
            r = random.choice(range(9))
            self.h.append(r)
            print "Rand in list:", self.h
            time.sleep(random.randint(1, 100)/100.0)

    def part2(self):
        while True:
            if self.h:
                print "Get:", self.h.pop()


if __name__ == "__main__":
    obj = GenerateRand()
    th1 = Thread(target = obj.part1)
    th2 = Thread(target = obj.part2)
    th1.start()
    th2.start()
    th1.join()
    th2.join()

這很好,但是來自線程的打印是混合的。 這段代碼好嗎? 是否有更好的(“pythonic”:)方式來做到這一點?

這是一個典型的生產者 - 消費者問題。 最好使用Queue在線程之間傳遞消息(在你的情況下消息是r中的隨機數),以避免繁忙等待,這會消耗不必要的CPU時間。 Queue.get()允許等待下一條消息非繁忙。

除此之外,你的解決方案很好。 這正是你如何實現這樣的流程。 我個人更喜歡子類threading.Thread而不是使用target參數,但對於簡單的情況,使用target很好。 更多細節在這里 )。

當然,打印輸出是“混合”的。 打印命令輸出到同一位置(stdout),並且不保證執行它們的順序。 畢竟,他們是不同的線程......

如果要避免文本輸出被擾亂,可以向類添加鎖定

class GenerateRand:
    def __init__(self):
        self.h = []
        self.lock = threading.Lock()

    def part1(self):
        while True:
            r = random.choice(range(9))
            self.lock.acquire()
            self.h.append(r)
            print("added: " + str(self.h))
            self.lock.release()
            time.sleep(random.randint(1,100)/100.0)
    def part2(self):
        while True:
            if self.h:
                self.lock.acquire()
                print( "popped: " + str( self.h.pop()))
                self.lock.release()

暫無
暫無

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

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