运行两个独立的交流线程

时间:2014-10-22 07:15:18

标签: python multithreading

我想运行一个显示由另一个(线程)计算的数据而不等待它的线程。 和平的代码试图解释它(python3):

from time import sleep, time


class Display:

    def __init__(self):
        self._current_frame = 0
        self._data = 0

    def run(self):
        start_time = time()
        while True:  # Expect: infinite loop still Core is running
            sleep(0.5)
            self._current_frame = i
            print(round(time()-start_time, 2), 'Display frame is', self._current_frame, 'and data is', self._data)

    def receive(self, data):
        self._data = data


class Core:

    def __init__(self):
        self._display = Display()

    def start(self):
        # Expected: Run Display in thread and continue
        self._display.run()
        for i in range(10):
            sleep(2)
            # When Core finish to compute a frame, It send data to the thread
            self._display.receive(i)

core =  Core()
core.start()

我想要的是:显示独立于核心计算打印他的消息。 Regulary,Core发送到显示新数据。显示器不必等待Core。

与流程管道一样。

输出应为:

0.5 Display frame is 0 and data is 0
1.0 Display frame is 1 and data is 0
1.5 Display frame is 2 and data is 0
2.0 Display frame is 3 and data is 1
2.5 Display frame is 4 and data is 0
3.0 Display frame is 5 and data is 0
3.51 Display frame is 6 and data is 0
4.01 Display frame is 7 and data is 2
4.51 Display frame is 8 and data is 0
5.01 Display frame is 9 and data is 0
[...]

我可以用线程做到吗?如果是的话怎么样?

0 个答案:

没有答案