python多线程 - 与输出混淆

时间:2018-02-17 07:10:14

标签: python multithreading parallel-processing python-multithreading

我正在尝试创建一个多线程程序,它将运行一个线程三秒钟,然后暂停'线程使用事件对象,等待几秒钟,然后重复该过程。这是我的代码:

import threading
import time

counter = 1 

def control():
    global counter
    test_event.wait()
    while(test_event.is_set()):
        print 'waiting 3 seconds'
        time.sleep(3)
        event.set()
        time.sleep(3)
        event.clear()
        if(counter == 1):
            counter = counter - 1

def function():
    global counter
    event.wait()
    while (event.is_set()):
        test_event.clear()
        print 'event is set to high'
        time.sleep(1)
    print 'event is set to low'
    test_event.set()

event = threading.Event()
test_event = threading.Event()

t1 = threading.Thread(target = control)
t2 = threading.Thread(target = function)

t1.start()
t2.start()

while(counter == 1):
    test_event.set()

我想要的输出应该是这样的:

waiting 3 seconds
event is set to high
event is set to high
event is set to high
event is set to low
waiting 3 seconds
event is set to high
....
....
and that keeps repeating.

我目前收到的输出是:

waiting three seconds
event is set to high
event is set to high
event is set to high
waiting 3 seconds

event is set to low 
waiting 3 seconds
waiting 3 seconds 
waiting 3 seconds
...
...
and that keeps repeating.

有人可以检测到我搞砸的地方,并可能提供任何建议让我解决?我似乎无法弄清楚我做错了什么。

P.S。我知道这段代码的构造可能很差,但我对多线程完全不熟悉...提前抱歉!

0 个答案:

没有答案