【问题标题】:Python daemon threads seems not work in backgroundPython 守护程序线程似乎无法在后台运行
【发布时间】:2019-09-25 19:00:41
【问题描述】:

我从https://www.bogotobogo.com/python/Multithread/python_multithreading_Daemon_join_method_threads.php 中获取了一段代码并添加了三行代码,期望它可以运行一个删除任何名为 'Tested' 的文件的守护进程。它在开始时工作,但如果在运行守护进程时(我猜它做到了),我使用“触摸测试”从命令行(在 GNU/linux 中)创建一个新文件,什么也没有发生。我读过它,但如果真的线程守护进程在后台工作,我应该做错了。

import threading
import time
import logging
import os
logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-9s) %(message)s',)

def n():
    logging.debug('Starting')
    logging.debug('Exiting')

def d():
    logging.debug('Starting')
    #  I expected these three following lines keep running in the background and delete any new file named 'Test'

    while True:
        if os.path.isfile('test'):
            os.remove ('test')

    time.sleep(5)
    logging.debug('Exiting')

if __name__ == '__main__':

    t = threading.Thread(name='non-daemon', target=n)
    d = threading.Thread(name='daemon', target=d)
    d.setDaemon(True)

    d.start()
    t.start()

【问题讨论】:

  • 我猜主程序退出了。因为您没有将线程重新加入主线程..尝试将其重新加入主线程
  • 但是加入等待所有加入的线程都完成了。我想要一个线程“永远”运行。我的问题是为什么里面的代码不起作用
  • 你可以尝试将睡眠功能移到 while true 块下吗?
  • Yatish,我解决了问题:d.setDaemon(True) 不起作用。我用 d.setDaemon = True 替换这条指令,效果很好。谢谢
  • 我也试过 d = threading.Thread(name='daemon', target=d, daemon = True) 但不起作用。

标签: python python-3.x python-multithreading python-daemon


【解决方案1】:

一旦主线程退出,守护线程就会被杀死(参见上面的文档this):

ForceBru:~ forcebru$ cat test.py
import threading
import time

def daemon():
    print('Daemon started')
    i = 0
    while True:
        print('Daemon running:', i)
        i += 1

d = threading.Thread(target=daemon, daemon=True)
d.start()
print('Started daemon!')
time.sleep(0.01)
print('Main thread is exiting. See if the daemon thread exits too')
ForceBru:~ forcebru$ python3 test.py
Daemon started
Daemon running: 0
Daemon running: 1
Daemon running: 2
Daemon running: 3
Started daemon!
Daemon running: 4
Daemon running: 5
Daemon running: 6
Daemon running: 7
Daemon running: 8
Daemon running: 9
Daemon running: 10
Daemon running: 11
<snip>
Daemon running: 1508
Daemon running: 1509
Daemon running: 1510
Main thread is exiting. See if the daemon thread exits too
Fatal Python error: could not acquire lock for <_io.BufferedWriter name='<stdout>'> at interpreter shutdown, possibly due to daemon threads

Thread 0x0000700008819000 (most recent call first):
  File "test.py", line 8 in daemon
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865 in run
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917 in _bootstrap_inner
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 885 in _bootstrap

Current thread 0x0000000104ea95c0 (most recent call first):
Abort trap: 6
ForceBru:~ forcebru$ 

你不一定会得到错误,但还是看看它说了什么:

Fatal Python error: could not acquire lock for <_io.BufferedWriter name='<stdout>'> at interpreter shutdown, possibly due to daemon threads

因此,Python 试图在守护线程仍在运行时自行关闭。因此,您的脚本实际上退出了,因为根据文档:

...当只剩下守护线程时,整个 Python 程序 退出

【讨论】:

    猜你喜欢
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多