• 线程池的简单实现


    池:存任务的空间,存入多个线程就叫线程池。(每个线程开启关闭耗费资源,线程池统一管理,线程可重复使用

    重复利用的线程池,代码实现:

    # -*- coding: utf-8 -*-
    """ 重复利用的线程池 """
    from threading import Thread, current_thread
    from queue import Queue
    import time
    
    
    class MyThreadPool:
        def __init__(self, n):
            self.queue = Queue()
            # 生成线程池
            for i in range(n):
                Thread(target=self.run, args=(self.queue, ), daemon=True).start()
    
        def run(self, queue):
            while True:
                task, args, kwargs = self.queue.get()
                task(*args, **kwargs)
                print(current_thread(), task) # 打印当前线程
                self.queue.task_done() # 计数器 -1
    
        def join(self):
            # queue计数为0时终止程序
            self.queue.join() # 重写thread join方法,调用queue join
    
        def apply_async(self, func, args=(), kwargs={}):
            self.queue.put((func, args, kwargs)) # 计数器 +1
    
    
    def apply1(n, m):
        # print('apply1: n+m=', n+m)
        time.sleep(3)
    
    def apply2(n, m):
        # print('apply2: n+m=', n+m)
        time.sleep(3)
    
    
    if __name__ == '__main__':
        my_thread_pool = MyThreadPool(3)
        my_thread_pool.apply_async(apply1, args=(1, 1))
        my_thread_pool.apply_async(apply2, args=(2, 2))
        my_thread_pool.apply_async(apply1, args=(1, 1))
        my_thread_pool.apply_async(apply2, args=(2, 2))
        my_thread_pool.apply_async(apply1, args=(1, 1))
        my_thread_pool.apply_async(apply2, args=(2, 2))
        # 主线程先执行到这儿,此时queue计数器 +1 *6
        my_thread_pool.join() # 等待计数器为0时结束队列queue阻塞程序
  • 相关阅读:
    转 子查询
    260@365
    线程池
    转 nio    netty
    正则表达式匹配标签内的内容
    express接受ajax的发送post请求
    如何查看代码使用率
    ajax传文件用express的multer接住
    ajax 的post方法 的content-type设置和express里应用body-parser
    webpack4 es6转换
  • 原文地址:https://www.cnblogs.com/tangpg/p/10638495.html
Copyright © 2020-2023  润新知