看看这个简单的 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()
它生成一个每秒输出“HELLO”的线程,然后进入 gobject 主循环。问题是它实际上并没有做任何事情。为什么?
$ python a.py
[...]
但是,如果我按下 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
[...]
看看第二个程序,除了它告诉 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()
运行它:
$ 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
再一次,按 CTRL+C 使生成的线程工作。为什么?
这是使用库 pygobject-2.28.6。
最佳答案
您需要initialize threading使用 gobject
时。为此,请调用
gobject.threads_init()
关于Python 线程不适用于 pygobject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16312928/