I have a typical multiple producers with a single consumer using python subprocess and one queue. The consumer has a callback to another object. Although the object is shared with all the subprocesses, when the subprocesses are finished, the changes to the object are lost.
Here's the code:
from multiprocessing import Process, Queue
import random
import time
class Manager(object):
def __init__(self):
self.queue = Queue()
def consume(self, call_back):
while True:
task = self.queue.get()
if task is None:
self.queue.close()
break
time.sleep(0.05)
call_back(task)
print("Queue got task: {}.".format(task))
def produce(self, value):
time.sleep(random.uniform(0.1, 1.0))
task = "TSK {}".format(value)
self.queue.put(task)
def start(self, call_back, n_tasks=10):
consumer = Process(target=self.consume, args=(call_back,))
consumer.start()
workers = [Process(target=self.produce,args=(i,))
for i in range(n_tasks)]
for w in workers:
w.start()
for w in workers:
w.join()
self.queue.put(None)
consumer.join()
class Display(object):
def __init__(self):
self.tasks = []
def display_tasks(self, n_tasks=10):
def add_task(task):
self.tasks.append(task)
print("Dislaying tasks so far: {}".format(self.tasks))
Manager().start(add_task, n_tasks)
print("Total tasks: {}".format(self.tasks))
Display().display_tasks(5)
The output is:
Dislaying tasks so far: ['TSK 3']
Queue got task: TSK 3.
Dislaying tasks so far: ['TSK 3', 'TSK 4']
Queue got task: TSK 4.
Dislaying tasks so far: ['TSK 3', 'TSK 4', 'TSK 2']
Queue got task: TSK 2.
Dislaying tasks so far: ['TSK 3', 'TSK 4', 'TSK 2', 'TSK 0']
Queue got task: TSK 0.
Dislaying tasks so far: ['TSK 3', 'TSK 4', 'TSK 2', 'TSK 0', 'TSK 1']
Queue got task: TSK 1.
Total tasks: []
And I was expecting:
Total tasks: ['TSK 3', 'TSK 4', 'TSK 2', 'TSK 0', 'TSK 1']
Any idea how this can be accomplished without:
class Display(object):
def __init__(self):
manager = Manager()
self.tasks = manager.list()
In fact in the real case this is using QTableWidget
and every entry in the table is a QTableWidgetItem
....
Here it is the real call back function (data_set_table
is a QTableWidget
):
def _add_item(data):
row = dc.size()
self._content.data_set_table.insertRow(row)
for i in range(len(data)):
if data[i] is not None:
item = QtGui.QTableWidgetItem(str(data[i]))
item.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
self._content.data_set_table.setItem(row, i, item)