【发布时间】: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