Skip to content

Chapter07/example1.py has some logic issues #1

@4honor

Description

@4honor

Problem

The code in the consumer class doesn't guarantee that although the queue has more than two elements, a single consumer can get all the two element. Because other consumers will compete for these elements too, which will often result in a situation that the two elements are got by two different consumers, therefore making the control variable result_size work in an unexpected manner.

Solution

Add a lock when get element from queue.

lock = multiprocessing.Lock()

class ReductionConsumer(multiprocessing.Process):
    def __init__(self, task_queue, result_queue):
         ...

    def run(self):
        pname = self.name
        print("Using process %s..." % pname)

        while True:
            with lock:
                num1 = self.task_queue.get()
                ...
                self.task_queue.task_done()
                self.result_queue.put(num1 + num2)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions