File: patcher_fork_after_monkey_patch.py

package info (click to toggle)
python-eventlet 0.40.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,200 kB
  • sloc: python: 25,101; sh: 78; makefile: 31
file content (70 lines) | stat: -rw-r--r-- 2,265 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Monkey patching interferes with threading in Python 3.7
# https://github.com/eventlet/eventlet/issues/592
__test__ = False


def check(n, mod, tag):
    assert len(mod._active) == n, 'Expected {} {} threads, got {}'.format(n, tag, mod._active)


if __name__ == '__main__':
    import eventlet
    import eventlet.patcher
    eventlet.monkey_patch()
    import os
    import sys
    import threading
    _threading = eventlet.patcher.original('threading')
    import eventlet.green.threading

    global threads_keep_running
    threads_keep_running = True

    def target():
        while threads_keep_running:
            eventlet.sleep(0.001)

    threads = [
        threading.Thread(target=target, name='patched'),
        _threading.Thread(target=target, name='original-1'),
        _threading.Thread(target=target, name='original-2'),
        eventlet.green.threading.Thread(target=target, name='green-1'),
        eventlet.green.threading.Thread(target=target, name='green-2'),
        eventlet.green.threading.Thread(target=target, name='green-3'),
    ]
    for t in threads:
        t.start()

    check(5, threading, 'pre-fork patched')
    check(3, _threading, 'pre-fork original')
    check(5, eventlet.green.threading, 'pre-fork green')

    pid = os.fork()
    if pid == 0:
        # Inside the child, we should only have a main _OS_ thread,
        # but green threads should survive.
        check(5, threading, 'child post-fork patched')
        check(1, _threading, 'child post-fork original')
        check(5, eventlet.green.threading, 'child post-fork green')
        threads_keep_running = False
        sys.exit()
    else:
        wait_pid, status = os.wait()
        exit_code = os.waitstatus_to_exitcode(status)
        assert wait_pid == pid
        assert exit_code == 0, exit_code

    # We're in the parent now; all threads should survive:
    check(5, threading, 'post-fork patched')
    check(3, _threading, 'post-fork original')
    check(5, eventlet.green.threading, 'post-fork green')

    threads_keep_running = False

    for t in threads:
        t.join()

    check(1, threading, 'post-join patched')
    check(1, _threading, 'post-join original')
    check(1, eventlet.green.threading, 'post-join green')
    print('pass')