python - 在 Python 2.7 中使用线程 smtpd 的 linux 和 os x 之间的奇怪行为差异

标签 python linux multithreading macos smtpd

我有一个线程化的 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 上速度较慢的部分。

最佳答案

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

关于python - 在 Python 2.7 中使用线程 smtpd 的 linux 和 os x 之间的奇怪行为差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25830057/

相关文章:

windows - 文本文件的元数据

c# - 在 .NET 4.5 中并行运行 .exe 进程并更新进度条

python - 值错误: all the input array dimensions except for the concatenation axis must match exactly

linux - 如何走内核的VMA?

Linux:多核 CPU 中的进程和线程

c - 关闭套接字的问题

multithreading - 刷新 Realm 的成本是多少?

python - 如何使用 Python ConfigParser 从 ini 文件中删除一个部分?

python - 一张图表在 Bokeh 中有两个不同的 y 轴范围?

python - 在 python 中处理 Group4 TIFF 图像