Running two threads with the Multiprocessing library in Python, putting items into a queue in the daughter thread and getting them from the parents, hangs on the last item.
The question is why is that happening? And how do we get it to work?
The complete code is here. It is for an old USB spectrometer
https://drive.google.com/file/d/18kRFCnqO1GfAdrbgPYOFXp6LUdjy014s/view?usp=drive_link
https://drive.google.com/file/d/1Q0b0i_VLBBpKIapGReJ4wdVr1CiJHS1a/view?usp=drive_link
Following is a rough excerpt to describe what is the problem.
In the setup we have:
from multiprocessing import Process, Queue, Value
class Gizmo:
#blah blah blah, set up the hardware and create a multiprocessing Queue
self.dataqueue = Queue()
def startreader(self,nframes,nsets)
# clear the dataqueue
while not self.dataqueue.empty():
try:
self.dataqueue.get(False)
print( 'queue got entry' )
except Exception as e:
print( 'queue.get', e )
break
print( 'creating reader thread')
self.readerthread = Process( target = self.Reader_, args=(nframes,nsets) )
if self.readerthread is None:
print( 'creating reader thread failed')
return False
print( 'starting reader thread')
self.readerthread.start()
def Reader_(self,nrames,nsets):
#blah blah blah, get a bunch of records and then
for n,record in enumerate(records):
self.dataqueue.put( record )
print( 'reader put record', n )
return
def savedata(self)
while not self.dataqueue.empty():
print( 'getting record')
try:
record = self.dataqueue.get_nowait()
records.append(record )
print( 'got record')
except Exception as e:
print(e)
# blah blah blah and write it all to a disk file(changed $ to # while editing)
When we run this, we see four records pushed on to the queue from the reader, in the second thread.
reader put record 0
reader put record 1
reader put record 2
reader put record 3
And, then after seeing the reader exit, we call save(). We see 3 of the 4 records retrieved, and then it hangs on trying to get the fourth record.
getting records
getting record
got record
getting record
got record
getting record
got record
getting record
Again, the questions are:
Why does it hang?
And how do we get it to work?
queue.get_nowait()
? That doesn't sound right. Please see if you can create a minimal reproducible example. – HenningEmpty
exception if there are no items in the queue. So it never “stacks”, at least for such a reason. – Henningmultiprocessing.Queue.empty
method is not reliable. Read the docs. – Crigger