Queue在Python中可以算作是一种容器,但是他和list,set,dict不一样。

1. Queue不是Python内置类型。它在Queue模块中定义。

2. 它不是iterator容器,他不能使用for... in...语法进行遍历。(没有next方法),只能使用put,get进行存取包含的值。

3.它是线程安全的。可以在多线程环境下安全使用。(进程安全级别的Queue,需要使用multiprocessing.Queue。两者方法都是一致的)

好了上代码:

from Queue import Queue
from threading import Thread
def worker():
    while True:
        item = q.get()
        print(item)
        q.task_done() #

q = Queue()
num_worker_threads = 4
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in range(30):
    q.put(item)

q.join()       # block until all tasks are done

 

相关文章:

  • 2022-12-23
  • 2021-09-14
  • 2021-06-21
  • 2021-06-19
  • 2022-12-23
  • 2022-12-23
  • 2021-11-21
  • 2021-08-27
猜你喜欢
  • 2022-12-23
  • 2021-05-01
  • 2021-08-24
  • 2022-02-15
  • 2022-02-18
  • 2022-12-23
  • 2021-06-27
相关资源
相似解决方案