Python3多執行緒寫資料庫

2021-10-02 20:31:28 字數 2433 閱讀 1774

import pymysql

import threading

classdb:

def__init__

(self, host=

none

, username=

none

, pwd=

none

, dbname=

none):

self.pool =

self.host = host

self.username = username

self.pwd = pwd

self.dbname = dbname

defget_instance

(self)

:# 在連線池中為每個執行緒建立連線,並從連線池中獲取連線

name = threading.current_thread(

).name

if name not

in self.pool:

conn = pymysql.connect(self.host, self.username, self.pwd, self.dbname)

self.pool[name]

= conn

return self.pool[name]

class

multithreads

:def

__init__

(self, host=

none

, username=

none

, pwd=

none

, dbname=

none):

self.max_id =

10000

self.start_id =

1 self.db = db(host, username, pwd, dbname)

self.lock = threading.lock(

)def

insert_data

(self)

: db = self.db.get_instance(

) cursor = db.cursor(

)while

true

:if self.start_id >= self.max_id:

break

s = self.start_id

# 執行緒鎖

with self.lock:

self.start_id +=

50if self.start_id > self.max_id:

self.start_id = self.max_id

e = self.start_id

for i in

range

(s, e)

: sql =

"insert into ****** (id, name) values('{}', '{}')"

.format

(i, threading.current_thread(

).name)

try:

cursor.execute(sql)

db.commit(

)print

(threading.current_thread(

).name,

': '

, sql,

': success'

)except

: db.rollback(

)print

(threading.current_thread(

).name,

': '

, sql,

':failed'

)raise

defmain()

: multi_threads = multithreads(

'******x'

,'***xx'

,'***xx'

,'******'

) threads =

# 150為執行緒數量

for i in

range

(150):

t = threading.thread(target=multi_threads.insert_data)

t.start(

)for t in threads:

t.join(

)if __name__ ==

'__main__'

: main(

)

該示例**執行需要mysql資料庫,修改其中關於資料庫連線引數以及表的引數即可執行

結果:

Python3多執行緒

學習python執行緒 python3 執行緒中常用的兩個模組為 thread threading 推薦使用 thread 模組已被廢棄。使用者可以使用 threading 模組代替。所以,在 python3 中不能再使用 thread 模組。為了相容性,python3 將 thread 重新命名為...

python3 多執行緒

多執行緒簡介 執行緒 thread 也稱輕量級程序,時作業系統能夠進行運算排程的最小單位,它被包涵在程序之中,時程序中的實際運作單位。執行緒自身不擁有資源,只擁有一些在執行中必不可少的資源,但他可與同屬乙個程序的其他執行緒共享程序所擁有的全部資源。乙個執行緒可以建立和撤銷另乙個執行緒,同一程序中的多...

python3 多執行緒,執行緒鎖

python使用多執行緒,不一定執行速度快,這裡引入gil global interpreter lock python直譯器中任意時刻都只有乙個執行緒在執行 gil執行過程 1 設定乙個gil 2 切換執行緒去準備執行任務 runnale就緒狀態 3 執行 4 可能出現的狀態 執行緒任務執行結束 ...