方法:继承threading.Thread
示例为,python多线程并发修改数据库中一个表的同一行。
from time import time
import pymysql as MySQLdb
import threading
import random
import time
source_site = "us"
account_id = 101001
domain_num = 100
db_host = "10.64.22.200"
db_db = "hesui"
db_user = "uiadmin"
db_pwd = "uiadmin"
class DBProcessor:
def __init__(self, db_db, db_host, db_user, db_pwd):
self.conn = MySQLdb.connect(db_host, user=db_user, passwd = db_pwd, db=db_db)
def init_data(self):
sql = "insert into tb_cross_site_migration_history (license_acct_id, domain_number, imported_domain_number, source_site, create_time) values(%s, %s, 0, '%s', Now())"
cur = self.conn.cursor()
affectedRows = cur.execute(sql % (account_id, domain_num, source_site))
print(affectedRows)
self.conn.commit()
cur.close()
class myThread(threading.Thread):
def __init__(self, db_db, db_host, db_user, db_pwd):
threading.Thread.__init__(self)
self.conn = MySQLdb.connect(db_host, user=db_user, passwd = db_pwd, db=db_db)
def run(self):
# print("run")
try:
sql_update = "update tb_cross_site_migration_history set imported_domain_number = imported_domain_number + 1 where license_acct_id = %s"
cur = self.conn.cursor()
time.sleep(random.randint(0,5))
cur.execute(sql_update, account_id)
self.conn.commit()
cur.close()
time.sleep(1)
sql_select = "select imported_domain_number from tb_cross_site_migration_history where license_acct_id = %s"
cur = self.conn.cursor()
cur.execute(sql_select % account_id)
row = cur.fetchone()
cur.close()
if row is None:
print("fail")
num = row[0]
if num == domain_num:
print("yep, finish")
self.conn.close()
except Exception as ex:
print(ex)
if __name__ == '__main__':
print("start")
db_processor = DBProcessor(db_db,db_host,db_user,db_pwd)
db_processor.init_data()
for i in range(0,domain_num):
thread = myThread(db_db,db_host,db_user,db_pwd)
thread.start()
thread.join()
print("end")