创建守护进程线程
问题描述:
我正在尝试在Windows下创建守护程序线程,但是我不知道我在做什么错.下面的代码充当普通线程:我没有看到"End run"写入控制台.有什么建议吗?
I'm trying to create a daemon thread under Windows, but I have no clue what am I doing wrong. The code below is acting as a normal thread: I don't see "End run" written to the console. Any suggestions?
def start(self):
self.isrunning = True
self.thread = threading.Thread(name="GPS Data", target=self.thread_run)
self.thread.setDaemon(True)
self.thread.run()
print "End Run"
def thread_run(self):
while self.isrunning:
data = self.readline()
print(data)
答
以下内容:
self.thread.run()
应为:
self.thread.start()
否则,将在当前线程的上下文中而不是在新线程的上下文中调用thread_run()
.
Otherwise, thread_run()
is getting called in the context of the current thread, and not in the context of a new thread.
thread_run()
函数永远不会返回(因为self.isrunning
永远不会更改),并且代码也永远不会到达print
语句.
The thread_run()
function never returns (because self.isrunning
never changes), and the code never reaches the print
statement.