【问题标题】:Odd behavior difference between linux and os x with threaded smtpd in Python 2.7linux和os x之间的奇怪行为差异与Python 2.7中的线程smtpd
【发布时间】:2014-09-14 04:27:09
【问题描述】:

我有一个线程 smtp 服务器,它在 Linux(ubuntu 14.04 和 fedora 20)上比在 OS x (10.8) 上多花 20 秒才能停止。

from email.parser import Parser
from smtpd import SMTPServer as StdLibSmtpServer
from smtplib import SMTP
from threading import Thread
import asyncore
import re
import select
import logging
import os.path
import datetime
import json
import random
from socket import gethostname
class SmtpServer(StdLibSmtpServer, object):
    def __init__(self, listen='localhost', port=10025,
            forward_address='localhost', forward_port=10026):
        super(SmtpServer, self).__init__((listen, port), None)
        self.forward_address = forward_address
        self.forward_port = forward_port
        self._thread = None
        self._smtp = SMTP()
        self._should_re_raise_exceptions = False
    def start(self):
        if self._thread:
            raise Exception("Already running")
        logging.debug("Starting up")
        self._thread = Thread(target=self._thread_func)
        self._thread.daemon = True
        self._thread.start()
        logging.info("Started")
    def stop(self):
        if not self._thread:
            raise Exception("Not running")
        logging.debug("Stopping")
        self.close()
        self._thread.join()
        self._thread = None
        logging.info("Stopped")
    def _thread_func(self):
        try:
            asyncore.loop()
        except select.error:
            pass # socket was closed, we are shutting down

它发生在 self._thread.join() 行,我似乎可以找出原因。

有关如何进一步解决此问题的任何建议? 我通过以下方式运行文件:

from test import SmtpServer
serv = SmtpServer()
serv.start()
serv.stop()

serv.stop() 是 linux 上速度较慢的部分。

【问题讨论】:

  • 尝试将超时值设置为self._thread.join() — 即self._thread.join(timeout=0.5);

标签: python linux multithreading macos smtpd


【解决方案1】:

事实证明,根本原因是 asyncore.loop() 需要在使用 select 而不是 epoll 的系统上设置超时。非常感谢 @binarydud 提供的帮助。事实证明,在 thread.join 上设置一个短暂的超时也可以,但它可能会导致 asyncore 被孤立。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多