software-mariodiana
2/6/2016 - 7:35 PM

Combining the work of multiple threads.

Combining the work of multiple threads.

from multiprocessing import Process, Queue

def sieve(numbers):
    return tuple([n for n in numbers if n % 2 != 0])

def f(numbers, queue):
    n = sieve(numbers)
    queue.put(n)

components = (
    (3, 4, 5, 6, 7), 
    (8, 9, 10, 11, 12)
)

# "Queues are thread and process safe." 
#     Python docs - http://preview.tinyurl.com/nh8fzne
#
q = Queue()

p1 = Process(target=f, args=(components[0], q))
p2 = Process(target=f, args=(components[1], q))

p1.start()
p2.start()

p1.join()
p2.join()

a = q.get()
b = q.get()

# [3, 5, 7, 9, 11]
print sorted(set(a + b))