线程返回值

  1. 在方法变量中传入全局变量,在方法中对全局变量进行赋值

  2. (不堵塞)重新创建一个线程类,将方法写在run的方法中,然后run返回出结果在线程变量中,外部通过方法get到变量的值

    import time
    from threading import Thread
    
    def foo(number):
        time.sleep(20)
        return number
    
    class MyThread(Thread):
    
        def __init__(self, number):
            Thread.__init__(self)
            self.number = number
    
        def run(self):
            self.result = foo(self.number)
    
        def get_result(self):
            return self.result
    
    
    thd1 = MyThread(3)
    thd2 = MyThread(5)
    thd1.start()
    thd2.start()
    thd1.join()
    thd2.join()
    
    print(thd1.get_result())
    print(thd2.get_result())
    

    适合于 获取每一个线程的运算结果

  3. (阻塞)使用ThreadPoolExecutor的submit

    def thread_function(age):
        return age+1
     
    def run_thread_pool_sub(target, args, max_work_count=3):
        with ThreadPoolExecutor(max_workers=max_work_count) as t:
            res = [t.submit(target, i) for i in args]
            return res
        
    if __name__ == '__main__':
        ages = [1, 3, 4]
        res = run_thread_pool_sub(thread_function, ages)
        for future in as_completed(res):
            data = future.result()
            print dat
    

    通过future.result()获得结果 submit的返回是无序

  4. (阻塞)使用ThreadPoolExecutor的map

    def thread_function(age):
        for i in age:
            yield i+1
     
    def run_thread_pool(target, args, max_work_count=6):
        with ThreadPoolExecutor(max_workers=max_work_count) as t:
            res = t.map(target, args)
            return res
     
    if __name__ == '__main__':
        ages = [1, 3, 4]
        # 2222
        res = run_thread_pool(target=thread_function, args=(ages,))
        for j in res:
            for i in j:
                print i
    

    map的输出是有序

    参考:https://blog.csdn.net/qq_43178297/article/details/102805223

posted @ 2021-09-17 16:56  兔子春  阅读(137)  评论(0编辑  收藏  举报