Dog*_*Dog 5 python concurrency asynchronous gobject pygobject
看看这个琐碎的python gobject程序:
import threading
import gobject
import time
def f():
while True:
print "HELLO"
time.sleep(1)
threading.Thread(target=f).start()
gobject.MainLoop().run()
Run Code Online (Sandbox Code Playgroud)
它产生一个每秒输出"HELLO"的线程,然后进入gobject主循环.问题是它实际上没有做任何事情.为什么?
$ python a.py
[...]
Run Code Online (Sandbox Code Playgroud)
但是,如果我按CTRL + C,它就会开始工作.此外,删除程序(gobject.MainLoop().run())中的最后一行使它工作.为什么?
$ python a.py
^CTraceback (most recent call last):
File "a.py", line 11, in <module>
gobject.MainLoop().run()
KeyboardInterruptHELLO
HELLO
HELLO
HELLO
[...]
Run Code Online (Sandbox Code Playgroud)
看看第二个程序,它与第一个程序完全相同,只是它告诉gobject g每秒运行一次该函数.这种类型的工作,生成的线程每隔一段时间运行一次,而不是永远.为什么?
import threading
import gobject
import time
def f():
while True:
print "HELLO"
time.sleep(1)
threading.Thread(target=f).start()
def g():
print "yo"
return True
gobject.timeout_add_seconds(1, g)
gobject.MainLoop().run()
Run Code Online (Sandbox Code Playgroud)
运行它:
$ python b.py
HELLOyo
yo
yo
yo
HELLO
yo
yo
yo
yo
yo
yo
yo
HELLO
yo
yo
yo
yo
^CTraceback (most recent call last):
File "b.py", line 16, in <module>
gobject.MainLoop().run()
KeyboardInterrupt
HELLO
HELLO
HELLO
HELLO
HELLO
Run Code Online (Sandbox Code Playgroud)
再次,按CTRL + C使得生成的线程工作.为什么?
这是使用库pygobject-2.28.6.