如何使用偶数和奇数函数同步两个线程

时间:2017-03-09 08:22:04

标签: python multithreading python-2.7 python-3.x python-multithreading

如何在python中使用偶数和奇数函数同步两个线程

它必须返回如下值:

fun1 odd = 1
fun2 even =2
fun1 odd = 3
fun2 even =4
fun1 odd = 5
fun2 even =6

请提供任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以像此示例一样使用“Event”:

import threading


class PrintNumbers(threading.Thread):
    def __init__(self, start_number, end_number, step, set_event, clear_event):
        threading.Thread.__init__(self)
        self.start_number = start_number
        self.end_number = end_number
        self.step = step
        self.set_event = set_event
        self.clear_event = clear_event

    def run(self):
        for i in range(self.start_number, self.end_number, self.step):
            print(i)
            self.set_event.set()
            self.clear_event.clear()
            self.clear_event.wait()
        self.set_event.set()


threading_event1 = threading.Event()
threading_event2 = threading.Event()

t1 = PrintNumbers(0, 10, 2, threading_event1, threading_event2)
t2 = PrintNumbers(1, 10, 2, threading_event2, threading_event1)

t1.start()
t2.start()

t1.join()
t2.join()

此代码创建两个事件,一个事件用于在线程中设置它,另一个事件用于在同一线程中清除。每个线程设置另一个事件,并在清除事件后等待它的事件。