python获取多线程线程执行结果

python的threading模块有提供多线程的执行方法,在计算密集型操作里也用不上,很多时候是在处理IO密集型的操作里使用,能为我们节省不少时间,但他本身不提供获取线程执行结果,需要我们自行实现,目前最简单的办法就是使用Queue来实现,Queue在线程之间是共享的,并且本身就提供了良好的加锁机制,可以直接使用。
 

首先简单封装下threading模块,取名为mythreading.py:

# coding=utf-8
# python2适用 python3可能略有不同,请自行修改

import threading

class MyMutiThread():
    def __init__(self):
        self.runlist = list()

    def muti_thread_add(self, func, name, *args, **kwargs):
        t = threading.Thread(target=func, name=name, args=args, kwargs=kwargs)
        self.runlist.append(t)

    def muti_thread_start(self):
        for t in self.runlist:
            t.start()

    def muti_thread_wait(self):
        for t in self.runlist:
            t.join()

接下来具体实现多线程的方法:

# coding=utf-8

import Queue
import mythreading

def my_function(arg1):
    '''你的操作'''
    time.sleep(1)  #模拟你的操作
    result = "执行结果"
    result_q.put(result)

if __name__ == '__main__':
    # 开始处理并发
    result_q = Queue.Queue()   # 创建队列记录线程执行结果
    test_muti_thread = mythreading.MyMutiThread()
    test_muti_thread.muti_thread_add(my_function, "my_thread_name1", "arg1", result_q)
    test_muti_thread.muti_thread_add(my_function, "my_thread_name2", "arg2", result_q)
    test_muti_thread.muti_thread_start()
    test_muti_thread.muti_thread_wait()   # 等待执行完成
    result = list()
    while not result_q.empty():   # 校验执行结果
        result.append(result_q.get())
    print(result)   #获得结果



 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python支持多线程,可以使用threading模块来实现多线程。 1. 创建线程 使用threading.Thread()方法来创建线程,需要传入一个函数作为参数,该函数为线程执行体。 ```python import threading def print_hello(): print("Hello world!") t = threading.Thread(target=print_hello) t.start() ``` 2. 线程同步 线程同步是指多个线程在访问共享资源时,需要协调彼此的执行顺序,以避免出现竞态条件。Python提供了Lock、RLock、Semaphore、Condition等多种线程同步机制。 ```python import threading count = 0 lock = threading.Lock() def increment(): global count for i in range(1000000): lock.acquire() count += 1 lock.release() t1 = threading.Thread(target=increment) t2 = threading.Thread(target=increment) t1.start() t2.start() t1.join() t2.join() print("Count: ", count) ``` 在上面的例子中,使用Lock来保护共享变量count,防止两个线程同时修改count的值。 3. 线程间通信 在多线程编程中,线程之间需要进行通信,以便协调彼此的执行Python提供了Queue模块来实现线程间通信。 ```python import threading import queue q = queue.Queue() def producer(): for i in range(10): q.put(i) print("Produced:", i) def consumer(): while True: item = q.get() if item is None: break print("Consumed:", item) q.task_done() t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start() t1.join() q.put(None) t2.join() ``` 在上面的例子中,使用Queue模块来实现生产者-消费者模式的线程间通信。生产者线程向队列中放入数据,消费者线程从队列中取出数据进行处理。当生产者线程放入None时,表示队列中没有更多数据,消费者线程退出。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值