If self.Queue is empty, self.Queue.get() will throw a Queue.Empty exception. At this time, the thread will exit and there will be no working threads. Add try...except in the while loop of the run() method and try to catch the exception. The code is roughly as follows:
==================================================== ====================== First of all: As for the problem you said that mysql does not support multi-threaded writing, I simply wrote a verification program and concluded that mysql supports it. Multi-thread writing (note: in actual work, writing data to the db in multi-threads requires adding a lock mechanism, which is simplified here), the code is as follows:
In addition: Because I don’t know the specific details of your code, I can’t completely locate the problem. I wrote a simulation program myself, and it didn’t happen to you. I hope it will be helpful to you. The code is as follows:
#coding: utf-8
import Queue
import threading
class MyThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.setDaemon(True)
self.queue = queue
def run(self):
while True:
try:
task = self.queue.get(timeout=2)
print 'task: %s' % task
# 这里可以处理task
except Exception, err:
break
if __name__ == '__main__':
threads = []
q = Queue.Queue()
for i in xrange(3):
thread = MyThread(q)
threads.append(thread)
for t in threads:
t.start()
for i in xrange(30):
q.put(i)
for t in threads:
t.join()
print '====== done ======'
Consumer join, try it, and then you judge the conditions. If the queue is empty, the loop breaks
If self.Queue is empty, self.Queue.get() will throw a Queue.Empty exception. At this time, the thread will exit and there will be no working threads.
Add try...except in the while loop of the run() method and try to catch the exception. The code is roughly as follows:
==================================================== ======================
First of all: As for the problem you said that mysql does not support multi-threaded writing, I simply wrote a verification program and concluded that mysql supports it. Multi-thread writing (note: in actual work, writing data to the db in multi-threads requires adding a lock mechanism, which is simplified here), the code is as follows:
In addition: Because I don’t know the specific details of your code, I can’t completely locate the problem. I wrote a simulation program myself, and it didn’t happen to you. I hope it will be helpful to you. The code is as follows: