mp_pool.py 3.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
import multiprocessing
import time
import random
import sys

#
# Functions used by test code
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % (
13
        multiprocessing.current_process().name,
14 15 16 17 18 19 20
        func.__name__, args, result
        )

def calculatestar(args):
    return calculate(*args)

def mul(a, b):
21
    time.sleep(0.5 * random.random())
22 23 24
    return a * b

def plus(a, b):
25
    time.sleep(0.5 * random.random())
26 27 28
    return a + b

def f(x):
29
    return 1.0 / (x - 5.0)
30 31

def pow3(x):
32
    return x ** 3
33 34 35 36 37 38 39 40 41 42

def noop(x):
    pass

#
# Test code
#

def test():
    PROCESSES = 4
43
    print('Creating pool with %d processes\n' % PROCESSES)
44

45 46 47 48
    with multiprocessing.Pool(PROCESSES) as pool:
        #
        # Tests
        #
49

50 51
        TASKS = [(mul, (i, 7)) for i in range(10)] + \
                [(plus, (i, 8)) for i in range(10)]
52

53 54 55
        results = [pool.apply_async(calculate, t) for t in TASKS]
        imap_it = pool.imap(calculatestar, TASKS)
        imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)
56

57 58 59 60
        print('Ordered results using pool.apply_async():')
        for r in results:
            print('\t', r.get())
        print()
61

62 63 64 65
        print('Ordered results using pool.imap():')
        for x in imap_it:
            print('\t', x)
        print()
66

67 68 69 70
        print('Unordered results using pool.imap_unordered():')
        for x in imap_unordered_it:
            print('\t', x)
        print()
71

72 73 74 75
        print('Ordered results using pool.map() --- will block till complete:')
        for x in pool.map(calculatestar, TASKS):
            print('\t', x)
        print()
76

77 78 79
        #
        # Test error handling
        #
80

81
        print('Testing error handling:')
82 83

        try:
84
            print(pool.apply(f, (5,)))
85
        except ZeroDivisionError:
86
            print('\tGot ZeroDivisionError as expected from pool.apply()')
87
        else:
88
            raise AssertionError('expected ZeroDivisionError')
89 90

        try:
91 92 93 94 95
            print(pool.map(f, list(range(10))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from pool.map()')
        else:
            raise AssertionError('expected ZeroDivisionError')
96 97

        try:
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
            print(list(pool.imap(f, list(range(10)))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from list(pool.imap())')
        else:
            raise AssertionError('expected ZeroDivisionError')

        it = pool.imap(f, list(range(10)))
        for i in range(10):
            try:
                x = next(it)
            except ZeroDivisionError:
                if i == 5:
                    pass
            except StopIteration:
                break
            else:
                if i == 5:
                    raise AssertionError('expected ZeroDivisionError')

        assert i == 9
        print('\tGot ZeroDivisionError as expected from IMapIterator.next()')
        print()

        #
        # Testing timeouts
        #

        print('Testing ApplyResult.get() with timeout:', end=' ')
        res = pool.apply_async(calculate, TASKS[0])
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % res.get(0.02))
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()

        print('Testing IMapIterator.next() with timeout:', end=' ')
        it = pool.imap(calculatestar, TASKS)
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % it.next(0.02))
            except StopIteration:
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()
149 150 151 152 153


if __name__ == '__main__':
    multiprocessing.freeze_support()
    test()