【问题标题】:ThreadPoolWorkers that will not die if they create a threadThreadPoolWorkers 如果他们创建一个线程就不会死掉
【发布时间】:2019-07-09 07:35:19
【问题描述】:

在我的 Slack RTM 消息处理函数中,我正在调用一组函数中的任何一个。单独来说,每个消息事件处理程序都会阻塞下一个,所以我开始在新线程中调用这些函数。完成此操作后,我无法 exit() 我的程序,我为每个被调用的消息处理程序留下了 ThreadPoolExecutor-x_x

即使我将线程设置为setDaemon=True.join(),ThreadPoolExecutors 仍然存在。

    def exitFunc(sendfn, channel, thread, user, text, groups, groupdict, meta):
        reply = 'bye'
        sendfn(channel=channel, message = reply)
        for thread in threading.enumerate():
            print(thread.getName())
        exit()

产生这个,然后挂起:

MainThread
ThreadPoolExecutor-0_0
ThreadPoolExecutor-0_1
ThreadPoolExecutor-3_0
ThreadPoolExecutor-3_1
ThreadPoolExecutor-3_2
exitFunc
ThreadPoolExecutor-3_3

当我不将函数作为新线程运行时,这些 ThreadPoolExecutors 似乎会挂起,但它们确实让我的程序退出。

产生线程:

def __init__(self, token, username = None, icon_emoji = None, security = None):
...
    slack.RTMClient.run_on(event='message')(self.readMessage)

def readMessage(self, **payload):
...
    thread = Thread(target=fn['fn'], kwargs = fnargs)
    thread.start()

作为 sendfn 传入的函数:

def sendMessage(self, channel, message, thread = None, username = None, icon_emoji = None):
    if username == None:
        username = self.default_username
    if icon_emoji == None:
        icon_emoji = self.default_icon_emoji

    print('{} Send to {}: {}'.format(str(datetime.now()), channel, message))

    self.webclient.chat_postMessage(
            channel=channel,
            text=message,
            username=username,
            icon_emoji=icon_emoji,
            thread_ts=thread
    )

我正在使用 slackclient 2.0.1 python 包。

【问题讨论】:

  • 你的函数sendfn是做什么的?请在您的问题中添加来源。另外:您是否使用任何库来处理 Slack RTM?
  • @ErikKalkoken 添加了

标签: python-3.x multithreading python-multithreading slack-api


【解决方案1】:

这是XY problem.

不是我的线程没有死,而是我试图从一个线程中退出()。

由于 exit() 最终“只”引发异常,它只会退出 从主线程调用时的进程,异常不是 被拦截了。

https://docs.python.org/2/library/sys.html#sys.exit

我将出口移到主线程,它退出正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    相关资源
    最近更新 更多