Home  >  Q&A  >  body text

多线程 - 关于Python Cookbook中创建线程池代码的一个bug?

黄舟黄舟2764 days ago363

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 10:06:12

    I think your statement is right.

    import time
    from Queue import Queue
    from threading import Thread, activeCount
    
    G_WORKER_NUM = 1
    G_COUNTER = 1
    
    def do_something(q):
        q.get()
        global G_COUNTER
        G_COUNTER += 1
        print(G_COUNTER)
    
    
    def main():
        q = Queue()
        for n in xrange(G_WORKER_NUM):
            t = Thread(target=do_something, args=(q,))
            t.start()
    
        q.put(('anything',))
        q.put(('anything',))
        q.put(('anything',))
    
    
    if __name__ == '__main__':
        main()
        time.sleep(2)
        print activeCount()

    Output:

    Indicates that the thread has indeed exited.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:06:12

    Perhaps the author just wanted to demonstrate creating a thread pool to limit the number of threads that can be opened, and did not consider the complete project. For example, the threads in the thread pool must be reusable and cannot be created and closed frequently; the size of the thread pool can be dynamically adapted. When there are a certain number of idle threads, some will be shut down. When the threads are full and there are not enough, appropriate Add some threads. Specifically, I think if you can look up relevant information, there will definitely be a solution.

    reply
    0
  • 阿神

    阿神2017-04-18 10:06:12

    He didn’t write in the main threadq.join()

    reply
    0
  • Cancelreply