python 多线程的学习历程

之前一直直接使用Thread去做python多线程的测试,start开始线程,然后join去等待结束等等。

import threading
import time

def add(x,y):
    print("the res is %d" % (x+y))
    time.sleep(x)
    print("the thread is over")

x1=1
x2=2
y1=1
y2=2
T_list=[]

T1 = threading.Thread(target=add,args=(x1,y1))
T_list.append(T1)
T2 = threading.Thread(target=add,args=(x2,y2))
T_list.append(T2)
for i in T_list:
    i.start()

for i in T_list:
    if i.joina
    i.join()
T1.join()
T2.jion

然后产生需求,需要对于返回值进行判断。使用了以下的函数去get_result

class EnhancedThread(Thread):
    def __init__(self, target, args):
        super(EnhancedThread, self).__init__()
        self.target = target
        self.args = args
    def run(self):
        self.result = self.target(*self.args)
    def get_result(self):
        try:
            return self.result
        except Exception:
            return -1

后来发现使用这个可能存在各种各样的问题,,需要手动的去start,单独的去包装修饰一个已有的类会显得特别的冗余,所以开始使用concurrent中的ThreadPoolExecutor去做多线程的操作。

通过executor = ThreadPoolExecutor(最大线程数)进行初始化。

然后利用submit将函数加入线程池并开始运行,

from concurrent.futures import ThreadPoolExecutor,as_completed
import time

def wait_and_print(wait_time):
    time.sleep(wait_time)
    print("Has wait for %d seconds"%wait_time)
    if wait_time== 3:
        return False
    return True

def get_result(future):
    return futrue.result()

def run():
    executor = ThreadPoolExecutor()
    task_list =[]
    for i in range(4):
        temp_process = executor.submit(wait_and_print,i)
        task_list.append(temp_process)
    for i in as_completed(task_list):
        #res = i.result()
        res=i.add_done_callback(get_result)
        print("The res is % d" % res)
        time.sleep(0.5)

    executor.shutdown(wait=True)

run()

但是本人在实际使用中发现,运行到as_completed时可能会程序突然终止,程序在运行50次之后可能发生该现象,到现在也没有发现为啥。十分不解。十分疑惑。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值