多线程 - 关于Python Cookbook中创建线程池代码的一个bug?
黄舟
黄舟 2017-04-18 10:04:12
0
3
335
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
左手右手慢动作

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.

黄舟

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.

阿神

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!