1. 多线程处理
先计算 num - 1,返回
再计算 add(num)
from concurrent.futures import ThreadPoolExecutor
import time
import logging
import traceback
"""
多线程处理
"""
def add(num):
return num+1
class CreditService():
def __init__(self, thread_pool_num):
self.thread_pool = ThreadPoolExecutor(thread_pool_num)
self.thread_pool_num = thread_pool_num
self.task_handler_list = []
def extract_credit_service(self, name, num):
task_handler = self.thread_pool.submit(lambda p: self.main_credit_service(*p), [name, num])
self.task_handler_list.append(task_handler)
while True:
for task_handler_tmp in self.task_handler_list:
if task_handler_tmp.done():
self.task_handler_list.remove(task_handler_tmp)
if len(self.task_handler_list) > 2 * self.thread_pool_num:
time.sleep(10)
else:
return True
def main_credit_service(self, name, num):
try:
num_add = add(num)
time.sleep(5)
print(name, num_add)
except Exception as e:
traceback.print_exc()
traceback.print_exc(file=open('log.txt', 'a'))
thread_pool_num = 2
credit_service = CreditService(thread_pool_num) # 只初始化一次
def mianmian(st, i):
credit_service.extract_credit_service(st, i)
return i-1
if __name__ == "__main__":
print(mianmian("aa",3))
print(mianmian("bb",4))
print(mianmian("cc",5))
输出:
2
3
4
aa 4
bb 5
cc 6
2. 多线程处理,add函数为异步
import asyncio
async def add(num): # 异步函数
return num+1
# 将异步函数转为同步函数
def sync_add(num):
# 使用 asyncio.run 来运行异步的 add
return asyncio.run(add(num))
整体:
from concurrent.futures import ThreadPoolExecutor
import time
import logging
import traceback
import asyncio
"""
多线程处理
"""
async def add(num): # 异步函数
return num+1
class CreditService():
def __init__(self, thread_pool_num):
self.thread_pool = ThreadPoolExecutor(thread_pool_num)
self.thread_pool_num = thread_pool_num
self.task_handler_list = []
def extract_credit_service(self, name, num):
task_handler = self.thread_pool.submit(lambda p: self.main_credit_service(*p), [name, num])
self.task_handler_list.append(task_handler)
while True:
for task_handler_tmp in self.task_handler_list:
if task_handler_tmp.done():
self.task_handler_list.remove(task_handler_tmp)
if len(self.task_handler_list) > 2 * self.thread_pool_num:
time.sleep(10)
else:
return True
def main_credit_service(self, name, num):
try:
num_add = asyncio.run(add(num))
time.sleep(5)
print(name, num_add)
except Exception as e:
traceback.print_exc()
traceback.print_exc(file=open('log.txt', 'a'))
thread_pool_num = 2
credit_service = CreditService(thread_pool_num) # 只初始化一次
def mianmian(st, i):
credit_service.extract_credit_service(st, i)
return i-1
if __name__ == "__main__":
print(mianmian("aa",3))
print(mianmian("bb",4))
print(mianmian("cc",5))