• 线程池的要点分析


    线程池的要点分析

    1、考虑建立线程数量

    2、线程池的状态

        with open('flog') as f:
    f.write()

    3、关闭线程

    实例(简单实例)

    原理:

    1:创建10个线程对象
    2:queue队列拿取线程。可用:拿;否则:等待
    3:线程执行完毕,归还给线程池
    #!/usr/bin/env python
    # coding:utf-8
    import  Queue
    import threading
    """
    1:创建10个线程对象
    2:queue队列拿取线程。可用:拿;否则:等待
    3:线程执行完毕,归还给线程池
    """
    class ThreadPool(object):
        # 设置一个默认参数max_num
        def __init__(self,max_num=20):
            # 创建队列
            self.queue = Queue.Queue(max_num)
            # 循环创建1个对象
            for i in xrange(max_num):
                self.queue.put(threading.Thread)
    
        def get_thread(self):
            return self.queue.get()
        # 使用类
        def add_thread(self):
            self.queue.put(threading.Thread)
    
    # 创建对象
    # 创建1最多能接收10个线程的队列
    pool = ThreadPool(10)
    
    def func(arg,p):
        print arg
        import time
        time.sleep(2)
        p.add_thread()
    # 300个任务要执行
    for i in xrange(300):
        # 获取一个线程,
        thread = pool.get_thread()
        # 执行这个线程
        t = thread(target=func,args=(i,pool))
        t.start()

    实例(twisted.python.threadpool)

    #!/usr/bin/env python
    # coding:utf-8
    import  contextlib
    doing = []
    
    @contextlib.contextmanager
    def show(li,item):
        # print "before"
        doing.append(item)
        yield
        doing.remove(item)
    
    print len(doing)
    
    with show(doing,1):
        print 'with in'
        print len(doing)
    
    print len(doing)

     

  • 相关阅读:
    Mybatis plus 多表连接分页查询
    webstorm自动格式化.vue文件并符合Eslint
    Selenium python爬虫
    Cent OS防火墙配置端口开放
    开发Hexo主题(一)
    谷歌开发者主页回归
    个人博客网站
    linux搭建ftp
    putty之pscp上传文件
    送走了最好的兄弟 收到上交复试通知
  • 原文地址:https://www.cnblogs.com/caoxiaojian/p/5130412.html
Copyright © 2020-2023  润新知