#coding=utf-8
import random
import string
import time
import threading
from threading import Lock
class MyThread(threading.Thread):
def __init__(self, func,arg=()):
# super(MyThread, self).__init__()
threading.Thread.__init__(self)
self.func = func
self.arg=arg
self.lock=Lock()
def run(self):
with self.lock:
self.result=self.func(*self.arg)
# self.result = self.func()
def get_result(self):
try:
return self.result
except Exception:
return None
def get_generateId(x,y):
strings = ''.join(random.sample(string.hexdigits, random.randint(x,y)))
# strings=eggroll.generateUniqueId()
return strings
def main(data_totalsNumber):
st=time.time()
thread_list = []
list_sampleIds=[]
for i in range(data_totalsNumber):
t = MyThread(get_generateId,arg=(16,18))
thread_list.append(t)
t.start()
for t in thread_list:
t.join()
list_sampleIds.append(t.get_result())
# print(list_sampleIds)
print(time.time()-st)
# real_idNumbers= len(set(list_sampleIds))
# assert real_idNumbers == data_totalsNumber
if __name__ == '__main__':
main(data_totalsNumber=200000)
cost 85.71295762062073
threadpool 模式线程池调用
import time
import threading
from concurrent.futures import ThreadPoolExecutor
class Account(object):
"""银行账户"""
def __init__(self):
self.balance = 0.0
self.lock = threading.Lock()
def deposit(self, money):
# 通过锁保护临界资源
with self.lock:
new_balance = self.balance + money
time.sleep(0.001)
self.balance = new_balance
class AddMoneyThread(threading.Thread):
"""自定义线程类"""
def __init__(self, account, money):
self.account = account
self.money = money
# 自定义线程的初始化方法中必须调用父类的初始化方法
super().__init__()
def run(self):
# 线程启动之后要执行的操作
self.account.deposit(self.money)
def main():
"""主函数"""
account = Account()
# 创建线程池
pool = ThreadPoolExecutor(max_workers=16)
futures = []
st = time.time()
for _ in range(400):
# 创建线程的第1种方式
# threading.Thread(
# target=account.deposit, args=(1, )
# ).start()
# 创建线程的第2种方式
# AddMoneyThread(account, 1).start()
# 创建线程的第3种方式
# 调用线程池中的线程来执行特定的任务
future = pool.submit(account.deposit, 1)
futures.append(future)
# 关闭线程池
pool.shutdown()
for future in futures:
future.result()
print("cost time",time.time()-st)
print(account.balance)
def main2():
pass
if __name__ == '__main__':
main()