[英]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”:)方式來做到這一點?
如果要避免文本輸出被擾亂,可以向類添加鎖定
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.