您现在的位置是: 网站首页> 学习笔记> python python

python清空ThreadPoolExecutor线程池中的所有任务

2022-06-15 [多线程] [线程池] 3439人已围观

最近有一个需求,关于多线程的,就是使用ThreadPoolExecutor开了一个线程池, 这个线程池一定会阻塞,因为每一个任务耗时30s,但是这个线程池新增任务时,之 前的任务可以取消,于是通过“python清空线程池”,“Python线程池清空任务”, “ThreadPoolExecutor清空任务”等关键词在网上搜解决方法,但都没有找到合适的, 后来去跟了一下ThreadPoolExecutor的源码,发现它的shutdown方法里有清空的 类似方法:

    def shutdown(self, wait=True):
        with self._shutdown_lock:
            self._shutdown = True
            self._work_queue.put(None)
        if wait:
            for t in self._threads:
                t.join()

self._work_queue.put(None)这个操作。

于是改吧改吧将就用着,虽然这样子不太好,但先解决问题,后面有其实方法再说哈哈

测试代码:

import time
from concurrent.futures import ThreadPoolExecutor

class TTest(object):
    def __init__(self):
        self.a = 0

    def abc(self, msg):
        print('print time: {}, value: {}'.format(time.time(), msg))
        time.sleep(5)

class TTest2(object):
    def __init__(self):
        self.pool = ThreadPoolExecutor(max_workers=5)
        self.tt = TTest()

    def run(self):
        for i in range(101):
            if i % 10 == 0:
                self.pool._work_queue.__init__()
            self.pool.submit(self.control, str(i))

        for i in range(200, 201):
            self.pool.submit(self.control, str(i))

    def control(self, msg):
        self.tt.abc(msg)

if __name__ == '__main__':
    t = TTest2()
    t.run()

主要代码

self.pool._work_queue.__init__()

测试结果

print time: 1655263586.1932056, value: 0
print time: 1655263586.1932056, value: 1
print time: 1655263586.1932056, value: 2
print time: 1655263586.1932056, value: 3
print time: 1655263586.1942031, value: 4
print time: 1655263591.1983352, value: 100
print time: 1655263591.1983352, value: 200

文章评论

暂无评论

添加评论





本栏推荐

站点信息

  • 建站时间:2021-01-01
  • 网站程序:Django 3.1.2
  • 文章统计:50篇
  • 文章评论:30条
  • 统计数据