Python中的简单线程示例

2024-09-27 21:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python中的线程有疑问(我承认,在这个问题上我是新手)。在

我有一个object,我想在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()

这很好用,但是线印是混合的。这个代码行吗? 有没有更好的(“Python”:)的方法?在


Tags: 方法代码importselfobjtimedef数字
2条回答

如果要避免文本输出被置乱,可以向类添加一个锁

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问题。最好使用^{}在线程之间传递消息(在您的例子中,消息是r中的随机数),以避免繁忙的等待,这会消耗不必要的cpu时间。Queue.get()允许在空闲时等待下一条消息。在

除此之外,你的解决方案很好。这正是实现这种流的方式。我个人更喜欢使用子类化threading.Thread,而不是使用target参数,但是对于简单的情况,使用target是可以的。(more details here)。在

当然,打印输出是“混合”的也是可以的。print命令输出到同一个位置(stdout),并且不能保证它们的执行顺序。毕竟,它们是不同的线程。。。在

相关问题 更多 >

    热门问题