python使用多執行緒查詢資料庫

2021-09-10 12:32:40 字數 3972 閱讀 1478

當資料量過大時,乙個程式的執行時間就會主要花費在等待單次查詢返回結果,在這個過程中cpu無疑是處於等待io的空閒狀態的,這樣既浪費了cpu資源,又花費了大量時間(當然這裡主要說多執行緒,批量查詢不在考慮範圍,總會存在不能批量查詢的情況),在這種非密集型運算(及大量占用cpu資源)的情況下在python中無疑運用多執行緒是乙個非常棒的選擇。

資料庫連線池的運用及優勢,python中多執行緒的運用,佇列的運用

資料庫連線池:限制了資料庫的連線最大個數,每次連線都是可以重複使用的,當然也可以限制每個連線的重複使用次數(這個在這裡是沒必要的),需要注意的是設定的資料庫的最大連線個數最好要大於我們自己開的最大執行緒個數,一般邏輯是每個執行緒占用乙個資料庫連線可以使程式達到最大速度,如果小於則可能存在同時連線個數大於資料庫允許的最大連線個數的風險。使用資料庫連線池的優勢在於,python多執行緒併發運算元據庫,會存在鏈結資料庫超時、資料庫連線丟失、資料庫操作超時等問題,而資料庫連線池提供執行緒間可共享的資料庫連線,並自動管理連線。

python多執行緒:在程式等待io的時間裡呼叫多執行緒去資料庫執行查詢操作。

佇列:這個就是資料結構裡面的知識了,一般佇列的常用模式先進先出佇列。(這裡主要用的是佇列取乙個數就少乙個數的原理,其實用列表也可以實現,他的先進先出主要強調的是乙個順序關係,這一點到沒用上,就當是練練手了)

資料庫的截圖:

第一段**:正常迴圈查詢並列印出執行時間

#!/usr/bin/python

# -*- coding=utf-8 -*-

import time

import threading

import mysqldb

import queue

from mysqldb.cursors import dictcursor

from dbutils.pooleddb import pooleddb

def mysql_connection():

host = 'localhost'

user = 'root'

port = 3306

password = '123456'

db = 'test'

charset = 'utf8'

limit_count = 3 # 最低預啟動資料庫連線數量

pool = pooleddb(mysqldb, limit_count, maxconnections=15, host=host, user=user, port=port, passwd=password, db=db, charset=charset,

use_unicode=true, cursorclass=dictcursor)

return pool

start = time.time()

pool = mysql_connection()

for id in range(50):

con = pool.connection()

cur = con.cursor()

sql = '''select id,name,age,weight from test where id = %s '''%id

cur.execute(sql)

time.sleep(0.5)

result = cur.fetchall()

if result:

print('this is tread %s (%s,%s,%s,%s)'%(id,result[0]['id'],result[0]['name'],result[0]['age'],result[0]['weight']))

else:

print('this tread %s result is none'%id)

end = time.time() - start

print(end)

執行結果:

第二段**:限制資料庫連線池最大15個連線,用佇列限制最大執行緒個數為10個

#!/usr/bin/python

# -*- coding=utf-8 -*-

import time

import threading

import mysqldb

import queue

from mysqldb.cursors import dictcursor

from dbutils.pooleddb import pooleddb

def mysql_connection():

host = 'localhost'

user = 'root'

port = 3306

password = '123456'

db = 'test'

charset = 'utf8'

limit_count = 3 # 最低預啟動資料庫連線數量

pool = pooleddb(mysqldb, limit_count, maxconnections=15, host=host, user=user, port=port, passwd=password, db=db, charset=charset,

use_unicode=true, cursorclass=dictcursor)

return pool

def tread_connection_db(id):

con = pool.connection()

cur = con.cursor()

sql = '''select id,name,age,weight from test where id = %s '''%id

cur.execute(sql)

time.sleep(0.5)

result = cur.fetchall()

if result:

print('this is tread %s (%s,%s,%s,%s)'%(id,result[0]['id'],result[0]['name'],result[0]['age'],result[0]['weight']))

else:

print('this tread %s result is none'%id)

con.close()

if __name__=='__main__':

start = time.time()

#建立執行緒連線池,最大限制15個連線

pool = mysql_connection()

#建立佇列,佇列的最大個數及限制執行緒個數

q=queue.queue(maxsize=10)

#測試資料,多執行緒查詢資料庫

for id in range(50):

#建立執行緒並放入佇列中

t = threading.thread(target=tread_connection_db, args=(id,))

q.put(t)

#佇列隊滿

if q.qsize()==10:

#用於記錄執行緒,便於終止執行緒

join_thread =

#從對列取出執行緒並開始執行緒,直到隊列為空

while q.empty()!=true:

t = q.get()

t.start()

#終止上一次隊滿時裡面的所有執行緒

for t in join_thread:

t.join()

end = time.time() - start

print(end)

程式備註應該還算比較清晰的哈,程式執行結果:

看結果說話

python使用多執行緒

做測試的時候,我們不得不接觸下多執行緒,雖然python不能發揮cpu多核的優勢,但是在測試的時候依然十分必要,比如在做介面測試的時候,發出請求之後,在等待伺服器端給予回應的時候,我們不應該傻傻地等,其它執行緒可以在等待的同時發出請求。這樣,我們就能更快地完成我們的測試任務。coding utf 8...

python 多執行緒使用

一 python中的執行緒使用 python中使用執行緒有兩種方式 函式或者用類來包裝執行緒物件。1 函式式 呼叫thread模組中的start new thread 函式來產生新執行緒。如下例 python view plain copy import time import thread def...

python多執行緒使用

一 簡介 由於python2逐漸不被維護,以及python更優越的效能。後面介紹的python相關知識都是用python3版本寫。這裡介紹python3的多執行緒相關知識,執行緒的建立使用threading包。二 簡單執行緒建立 簡介執行緒的建立,先定義執行任務的函式,然後呼叫threading.t...