【问题标题】:Restarting Threads in python and checking for exceptions在python中重新启动线程并检查异常
【发布时间】:2012-07-11 17:14:08
【问题描述】:

我已经绘制了我想要遵循的流程的流程图,但不知道如何执行此流程。目前我有以下内容。

t1 是一个数据库插入脚本,不是cherrypy。

def main():
    thread = ThreadUrl(queue)
    thread = thread()
    thread.start()
    cherrypy.config.update({'server.socket_host': '0.0.0.0',
                            'server.socket_port': 2970})
                            #'server.thread_pool': 100})
    queue.join()
    cherrypy.engine.start()
    while True:
        if thread.isAlive():
            try:
                cherrypy.engine.start()
            except Exception:
                print ('Started cherrypy already.')
            print ('I am alive.')
        else:
            try:
                thread.exit()
            except Exception:
                print ('Already killed this thread.')
            print ('I am dead.')
            try:
                cherrypy.engine.stop()
            except Exception:
                print ('Already stopped cherrypy.')
            try:
                thread.start()
            except Exception:
                print (sys.exc_info()[1])

if __name__ == '__main__':
    main()

【问题讨论】:

  • 这似乎...有点令人费解,因为cherrypy.engine 已经实现了自己的状态机,并且只有在调用cherrypy.engine.block() 时才会阻塞调用线程。你想用包装线程完成什么?
  • 嗨,对不起,我忘了在描述中添加一行很重要的内容,t1 是一个数据库插入脚本,不是cherrypy。

标签: python multithreading cherrypy python-multithreading


【解决方案1】:

您可以在字典中创建状态表。每个节点都在一个函数中,该函数执行其操作,然后返回下一个状态,如下所示:

def start_t1():
    # Start t1.
    return "start cherrypy"

def start_cherrypy():
    # Start Cherrypy.
    return "is t1 alive?"

def is_cherrypy_alive():
    # Check whether Cherrypy is alive.
    if alive:
        return "stop cherrypy"
    return "start t1"

actions = {
    "start t1": start_t1,
    "start cherrypy": start_cherrypy,
    "is t1 alive?": is_t1_alive,
    "is cherry pie alive?": is_cherrypy_alive,
    ...
}

state = "start t1"
while True:
    state = actions[state]()

【讨论】:

  • 嗨,对不起,我忘了在描述中添加一行很重要的内容,t1 是一个数据库插入脚本,不是cherrypy。
猜你喜欢
  • 1970-01-01
  • 2021-11-04
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2013-08-23
  • 2018-10-10
  • 2020-08-22
相关资源
最近更新 更多