Python如何实现多线程

方法:继承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")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值