我在python中测试多线程,但代码被挂起:
class MongoInsertThread(threading.Thread):
def __init__(self, queue, thread_id):
super(MongoInsertThread, self).__init__()
self.thread_id = thread_id
self.queue = queue
def run(self):
print(self.thread_id,': ', self.queue.get())
def save_to_mongo_with_thread():
q = queue.Queue()
size = int(math.ceil(16 / 3))
for e in range(size):
for i in range(e * size, min((e + 1) * size, 16)):
q.put([i], block=False)
threads = []
for i in range(size):
threads.append(MongoInsertThread(q, i))
for t in threads:
t.start()
for t in threads:
t.join()
print("+++++++++++++++++++++++")
结果是我想要的,但程序没有结束,结果是:
0 : [0]
1 : [1]
2 : [2]
3 : [3]
4 : [4]
5 : [5]
+++++++++++++++++++++++
0 : [6]
1 : [7]
2 : [8]
3 : [9]
4 : [10]
5 : [11]
+++++++++++++++++++++++
0 : [12]
1 : [13]
2 : [14]
3 : [15]
但是它不打印最后+++++++++++++++++++++++
,我该如何处理呢?
您正在调用q.put()
16
次 - 每产生e in range(5)
i in range(e * 5, (e + 1)*5)
-
i in range(0, 5)
-
i in range(5, 10)
-
i in range(10, 15)
-
i in range(15, 16)
-
i in range(20, 16)
-
i in range(25, 16)
这会将16
值附加到q
.但是,您创建25
线程,其中包含对q.get()
的关联25
调用 - 但是一旦前16
元素被get()
块中删除。如果您使用q.get(block=False)
代码将成功完成,但您将收到许多警告,从get()
引发Empty
。更改循环的循环条件
for i in range(size):
threads.append(MongoInsertThread(q, i))
到range(e * size, min((e + 1) * size, 16))
将修复不匹配。但是,添加 break 语句以在添加和删除所有元素后停止最外层for
循环也很有用16
。
完整示例
class MongoInsertThread(threading.Thread):
def __init__(self, queue, thread_id):
super(MongoInsertThread, self).__init__()
self.thread_id = thread_id
self.queue = queue
def run(self):
print(self.thread_id,': ', self.queue.get(block=False))
def save_to_mongo_with_thread():
q = Queue.Queue()
size = int(math.ceil(16 / 3))
for e in range(5):
if (e*size > 16):
break
for i in range(e * size, min((e + 1) * size, 16)):
q.put([i], block=False)
threads = []
for i in range(e * size, min((e + 1) * size, 16)):
threads.append(MongoInsertThread(q, i))
for t in threads:
t.start()
for t in threads:
t.join()
print("+++++++++++++++++++++++")
输出-
0: [0]
1: [1]
2: [2]
3: [3]
4: [4]
+++++++++++++++++++++++
5: [5]
6: [6]
7: [7]
8: [8]
9: [9]
+++++++++++++++++++++++
10: [10]
11: [11]
12: [12]
13: [13]
14: [14]
+++++++++++++++++++++++
15: [15]
+++++++++++++++++++++++
另请注意,我正在使用get(block = False)
来帮助阐明未来的问题,但对于此示例来说,这是不必要的。