有人可以指出,为什么我的代码不打印“你好”。我觉得我的线程2 - t2没有启动。这只是一个代码片段,我正在努力在我的主程序中实现。基本上,我的想法如下:
代码:
import threading
import Queue
def Continuous(stop_event, queue_read, queue_write,lock):
#lock.acquire()
try:
if stop_event == True:
print stop_event.is_set()
print "hello"
c = 7
d = 8
msg2 = (c+d)*2
queue_write.put(msg2)
while not stop_event.wait(1):
print "hello2"
#print ("working on %s" % arg)
a = 3;
b = 4
msg1 = a*b
queue_read.put(msg1)
time.sleep(1)
finally:
print "Inside finally"
#lock.release()
print"Outside try and finally"
def main():
pill2kill = threading.Event()
lock = threading.Lock()
pill2kill.clear()
queue1 = Queue.Queue()
queue2 = Queue.Queue()
#self.queue2 = Queue.Queue()
t1 = threading.Thread(target = Continuous, args = (pill2kill,queue1,queue2,lock))
t1.deamon = True
t1.start()
print "asdfasfd"
time.sleep(2)
pill2kill_1 = threading.Event()
pill2kill_1.set()
print "hjgkhj"
t2 = threading.Thread(target=Continuous, args=(pill2kill_1, queue1, queue2,lock))
t2.start()
t2.join()
pill2kill.clear()
print "End of program"
main()
PS:我非常抱歉,以这种方式发布我的代码。我尝试了超过15分钟,而且我无法将其格式化
答案 0 :(得分:0)
(由评论转换,因为OP的后续评论明确表达了他们的期望)问题来自于误用Event
:
if stop_event == True:
将始终评估为False
,而if
块永远不会执行其内容(stop_event
是Event
,它不相等对bool
类型的任何内容,您的意思是if stop_event.is_set():
?)。这样可以防止hello
被打印。while not stop_event.wait(1):
将立即退出循环而不执行正文(防止打印hello2
);唯一预期的输出来自finally
块,低于finally
。旁注:t1.deamon = True
什么都不做;该属性拼写为daemon
。由于你从来没有set
线程1的Event
,这似乎意味着程序永远不会退出。