【问题标题】:Python multithreading servicePython多线程服务
【发布时间】:2018-04-10 06:41:57
【问题描述】:

我正在尝试使用多个线程在 python 上创建 Windows 服务。 我编写了按我的需要工作的代码,但我不明白它是如何破坏线程的! 为什么break in while 循环会中断不在while 循环中的线程?

import win32serviceutil
import win32service
import win32event
import servicemanager
import threading
from classifier import clf, refit

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "MyService"
    _svc_display_name_ = "My Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop) 

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                          servicemanager.PYS_SERVICE_STARTED,
                          (self._svc_name_,'')) 
        self.main()

    def main(self):
        t1 = threading.Thread(target=clf)
        t2 = threading.Thread(target=refit)
        t1.start()
        t2.start()
        while True:        
            rc = win32event.WaitForSingleObject(self.hWaitStop, 100)
            if rc == win32event.WAIT_OBJECT_0:
                break  

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)   

【问题讨论】:

    标签: python multithreading winapi service


    【解决方案1】:

    SvcDoRun 返回时服务进程终止。这会使线程在其余过程中下降。如果您希望您的线程继续执行,那么您必须保持进程处于活动状态。换句话说,不要从SvcDoRun 返回。

    【讨论】:

    • 但是如果我需要线程连续工作并且仅在服务停止时终止,这是正确的方法吗?
    • 正确的方法是什么?我没有回答你的问题,这就是线程停止的原因。
    • 顺便说一句,这是标准 python 的相反行为,我认为这是 OP 的困惑的来源。如果你只是直接调用SvcDoRun,python 进程不会退出,因为线程是非守护进程的。 (假设基类没有从守护线程调用该方法。)线程被故意杀死作为服务终止的一部分,而不是解释器的普通操作。
    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 2013-02-11
    • 1970-01-01
    • 2022-01-23
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多