I use multithreading to insert data to database, but it cannot return correct result, the code is in belows:
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()
for e in range(3):
for i in range(10):
q.put([i], block=False)
threads = []
for i in range(5): ##(1)
threads.append(MongoInsertThread(q, i))
for t in threads:
t.start()
for t in threads:
t.join()
print("+++++++++++++++++++++++")
but the result generated by the code is:
0 : [0]
1 : [1]
2 : [2]
3 : [3]
4 : [4]
+++++++++++++++++++++++
0 : [5]
1 : [6]
2 : [7]
3 : [8]
4 : [9]
+++++++++++++++++++++++
0 : [0]
1 : [1]
2 : [2]
3 : [3]
4 : [4]
+++++++++++++++++++++++
which is not I wanted, and I hope the result is:
0 : [0]
1 : [1]
2 : [2]
3 : [3]
4 : [4]
0 : [5]
1 : [6]
2 : [7]
3 : [8]
4 : [9]
+++++++++++++++++++++++
0 : [0]
1 : [1]
2 : [2]
3 : [3]
4 : [4]
0 : [5]
1 : [6]
2 : [7]
3 : [8]
4 : [9]
+++++++++++++++++++++++
0 : [0]
1 : [1]
2 : [2]
3 : [3]
4 : [4]
0 : [5]
1 : [6]
2 : [7]
3 : [8]
4 : [9]
+++++++++++++++++++++++
Maybe in the for loop went some wrong, but I cannot find any solutions to deal with it. where is wrong with my code? And how can I deal with it?
And I use 11 to substitute 5 in ##(1), and it suspended, how can I deal with it?