python - 如何增加 Twisted 的连接池大小?

标签 python connection-pooling twisted

我使用 Twisted 8.1.0 作为套接字服务器引擎。 react 器 - epoll。数据库服务器是 MySQL 5.0.67。操作系统 - Ubuntu Linux 8.10 32 位

/etc/mysql/my.cnf 中:

max_connections        = 1000

在源代码中:

adbapi.ConnectionPool("MySQLdb", ..., use_unicode=True, charset='utf8', 
                      cp_min=3, cp_max=700, cp_noisy=False)

但实际上,当应用程序在高负载下运行时,我只能看到 200 个(或更少)打开的连接(SHOW PROCESSLIST)。这对我的应用程序来说还不够 :(

正如我所见,这是线程池的限制。有什么想法吗?

最佳答案

如您所料,这可能是线程问题。 cp_max 为线程池中的线程数设置上限,但是,您的进程很可能会耗尽远低于此限制的内存,在您的情况下约为 200 个线程。因为每个线程都有自己的堆栈,您的进程使用的总内存达到系统限制,无法创建更多线程。

您可以在运行程序之前通过调整堆栈大小 ulimit 设置(我正在使用 bash)来检查这一点,即

$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
max nice                        (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 32750
max locked memory       (kbytes, -l) 32
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
max rt priority                 (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 32750
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

您可以看到我机器上的默认堆栈大小为 10240K,我发现使用此设置可以创建大约 300 个线程。将堆栈大小调整到 1024K(使用 ulimit -s 1024)我可以创建大约 3000 个线程。

您可以使用此脚本了解您系统上的线程创建限制:

from thread import start_new_thread
from time import sleep

def sleeper():
    try:
        while 1:
            sleep(10000)
    except:
        if running: raise

def test():
    global running
    n = 0
    running = True
    try:
        while 1:
            start_new_thread(sleeper, ())
            n += 1
    except Exception, e:
        running = False
        print 'Exception raised:', e
    print 'Biggest number of threads:', n

if __name__ == '__main__':
    test()

这是否能解决您的问题将取决于 ConnectionPool 线程的内存要求。

关于python - 如何增加 Twisted 的连接池大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1171519/

相关文章:

python - 如何获得给定时区的 UTC 时间?

python - 将任务的结果输入到 Celery 中的 map 中

python - Pandas:处理具有多种数据类型的列

mysql - Django:汇集 MySQL 数据库连接

asp.net - 超时已过。在从池中获取连接之前超时时间已过。企业图书馆

python - 黑白图像上的子图像匹配

python - 如何检测服务器正在关闭UNIX域套接字?

twisted - Python扭曲的proxyclient级联/上游到squid

python - Zope 安装到错误的版本(easy_install 和 pip)