Python中的简单线程示例
作者:互联网
我对Python中的线程有疑问(我承认,我是这个主题的新手).
我有对象,我想在方法part1()中生成数字列表(具有一些随机时间间隔),并在part2()中生成-尽快打印所有生成的数字.
这是我的代码:
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()
标签:producer-consumer,multithreading,python 来源: https://codeday.me/bug/20191029/1962076.html