#不使用线程池 def hello_func(str): print(f"sql->>> {str}") time.sleep(2) sql_list = [ "select * from user;", "select * from user limit 10;", "show databases;" ] start_time = time.time() for i in range(len(sql_list)): hello_func(sql_list[i]) print(f'执行时间: {time.time()-start_time}s') #执行结果为6s多
import time, threadpool #使用线程池 def hello_func(str): print(f"sql->>> {str}") # [print(x) for x in range(1,5)] time.sleep(2) sql_list = [ "select * from user;", "select * from user limit 10;", "show databases;" ] start_time = time.time() list_num = len(sql_list) print(list_num) # 定义了一个线程池 pool = threadpool.ThreadPool(list_num) # 创建要开启多线程的函数,以及函数相关参数和回调函数,其中回调数可以不写,default是none requests = threadpool.makeRequests(hello_func, sql_list) # 将所有要运行多线程的请求扔进线程池 [pool.putRequest(req) for req in requests] # 所有的线程完成工作后退出 pool.wait() print(f'执行时间: {time.time()-start_time}s') #执行结果为2s多