【发布时间】:2020-04-17 07:35:30
【问题描述】:
from queue import Queue
import threading
import time
queue1 = Queue()
# this function should finish its work and restart with fresh queue1
def association_helper():
# this program should get the whole data from the queue, add into the list and print it. again it starts with
# remaining items in queue (the items which was inserting when this function printings the value)
lock = threading.Lock()
lock.acquire()
items = []
print("Start..")
while True:
if queue1.qsize()>0:
print("Line no 13:", queue1.qsize())
SizeofQueue1 = queue1.qsize()
for i in range(SizeofQueue1):
items.append(queue1.get())
queue1.task_done()
print("Line no 19:", len(items))
print(items)
print("Line no 25: done")
time.sleep(0.1)
lock.release()
i = 0
def main():
global i
# continuous data coming and adding in queue
while True:
queue1.put([i])
i += 1
if __name__ == '__main__':
# main thread will always run (adding the items in the queue)
f_thread = threading.Thread(target=association_helper)
f_thread.daemon = True
f_thread.start()
main()
output:
Start...
Line no 13: 1415
Line no 19: 3794
Line no 25: done
Line no 13: 40591
Line no 19: 41856
Line no 25: done
Line no 13: 78526
as per expectations, the line no 13 and line no 19 should be same. also, after, line no 25, it should print Start..(because association_helps should finish its execution and run again)
为什么association_helper 函数会运行一次?为什么它没有完成工作并在队列中使用新的剩余项目重新启动?
动机:
- queue1 将始终在主线程中添加新项目。
- 当 sizeof(queue1)>0 时,association_helper 应该从 queue1 中提取全部数据并处理数据。
- 但是应该继续在队列中添加项目
- association_helper 完成执行后,它应该从队列中的新项目重新开始。
【问题讨论】:
标签: python-3.x multithreading multiprocessing python-multiprocessing python-multithreading