网站制作学习网Python→正文:Python 多线程处理
字体:

Python 多线程处理

Python 2022/10/1 16:19:00  点击:不统计

<本文原载于www.forasp.cn>
 python 实现稳定的多线程

直接看下面代码



"""
@ 多线程处理
@ 切记 线程内部函数main出错,不会报错,需要先自行确定内部函数可用
"""
import time
from concurrent import futures


# 定义线程函数
def thread_ran():
thread_num_max = 5
tasks, results = [], []
with futures.ThreadPoolExecutor(max_workers=thread_num_max) as executor:
for i in range(thread_num_max):
tasks.append(executor.submit(run_default, i, thread_num_max))


def run_default(i, thread_num):
main_obj = main(thread_num, i) # 线程内的对象
main_obj.run() # 执行函数内方法


class main:
def __init__(self, thread_num, thread_index):
self.thread_num = thread_num
self.thread_index = thread_index

def run(self):
print("thread index", self.thread_index)
for i in range(10):
time.sleep(1)
print("Thread index", str(self.thread_index) + "_" + str(i))
print("run over")


# 开始执行函数
if __name__ == "__main__":
thread_ran()

%77w%77%2E%66%6F%72%61%73%70%2E%63%6E

·上一篇:pip is configured with locations that require TLS/SSL >>    ·下一篇:python except OSError, e: >>
推荐文章
最新文章