producer/consumer problem with python multiprocessing

前端 未结 3 720
鱼传尺愫
鱼传尺愫 2020-12-29 09:05

I am writing a server program with one producer and multiple consumers, what confuses me is only the first task producer put into the queue gets consumed, after which tasks

3条回答
  •  粉色の甜心
    2020-12-29 09:39

    I think there must be something wrong with the web server part, as this works perfectly:

    from multiprocessing import Process, Queue, cpu_count
    import random
    import time
    
    
    def serve(queue):
        works = ["task_1", "task_2"]
        while True:
            time.sleep(0.01)
            queue.put(random.choice(works))
    
    
    def work(id, queue):
        while True:
            task = queue.get()
            if task is None:
                break
            time.sleep(0.05)
            print "%d task:" % id, task
        queue.put(None)
    
    
    class Manager:
        def __init__(self):
            self.queue = Queue()
            self.NUMBER_OF_PROCESSES = cpu_count()
    
        def start(self):
            print "starting %d workers" % self.NUMBER_OF_PROCESSES
            self.workers = [Process(target=work, args=(i, self.queue,))
                            for i in xrange(self.NUMBER_OF_PROCESSES)]
            for w in self.workers:
                w.start()
    
            serve(self.queue)
    
        def stop(self):
            self.queue.put(None)
            for i in range(self.NUMBER_OF_PROCESSES):
                self.workers[i].join()
            self.queue.close()
    
    
    Manager().start()
    

    Sample output:

    starting 2 workers
    0 task: task_1
    1 task: task_2
    0 task: task_2
    1 task: task_1
    0 task: task_1
    

提交回复
热议问题