有一个sql,查询时间为3s。我认为,如果我创建3个线程,则每个线程几乎同时运行此sql,整个时间应几乎为3s。但实际上需要8秒为什么?
这样的代码:
import pymysql
import threading
import time
from config.db import db_config
def get_connection():
return pymysql.connect(**db_config)
def test(sql):
print('start query...')
st = time.time()
conn = get_connection()
cur = conn.cursor()
cur.execute(sql)
print('end query.. timeuse: ', time.time() - st)
def get_threads(num=3):
threads = []
for i in range(num):
threads.append(threading.Thread(target=test, args=(sql,)))
return threads
sql = "a sql cost 3s"
def main(num):
threads = get_threads(num)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
运行结果:
>>> main(1)
start query...
end query.. timeuse: 3.0793652534484863
>>> main(3)
start query...
start query...
start query...
end query.. timeuse: 7.348235368728638
end query.. timeuse: 7.411351919174194
end query.. timeuse: 8.129048585891724
备注:mysql引擎是innodb,max_connections是12384