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

3 投票
1 回答
3240 浏览
提问于 2025-04-15 13:06

我正在使用 Twisted 8.1.0 作为 socket 服务器引擎,使用的反应器是 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 查看)。这对我的应用来说不够 :(

我觉得这可能是线程池的限制。有没有什么建议?

1 个回答

8

正如你所猜测的,这可能是一个线程问题。cp_max 是用来设置线程池中线程数量的上限,但你的程序很可能在这个上限之前就已经耗尽了内存,在你的情况中大约是200个线程。因为每个线程都有自己的栈空间,所以你程序使用的总内存达到了系统的限制,这样就无法再创建更多的线程了。

你可以通过在运行程序之前调整栈大小的设置来检查这个问题(我使用的是 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 线程的内存需求。

撰写回答