Starts multiple worker processes. If ``num_processes`` is None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If ``num_processes`` is given and > 0, we fork that specific number of sub-processes. Since we use processes
(
num_processes: Optional[int], max_restarts: Optional[int] = None
)
| 80 | |
| 81 | |
| 82 | def fork_processes( |
| 83 | num_processes: Optional[int], max_restarts: Optional[int] = None |
| 84 | ) -> int: |
| 85 | """Starts multiple worker processes. |
| 86 | |
| 87 | If ``num_processes`` is None or <= 0, we detect the number of cores |
| 88 | available on this machine and fork that number of child |
| 89 | processes. If ``num_processes`` is given and > 0, we fork that |
| 90 | specific number of sub-processes. |
| 91 | |
| 92 | Since we use processes and not threads, there is no shared memory |
| 93 | between any server code. |
| 94 | |
| 95 | Note that multiple processes are not compatible with the autoreload |
| 96 | module (or the ``autoreload=True`` option to `tornado.web.Application` |
| 97 | which defaults to True when ``debug=True``). |
| 98 | When using multiple processes, no IOLoops can be created or |
| 99 | referenced until after the call to ``fork_processes``. |
| 100 | |
| 101 | In each child process, ``fork_processes`` returns its *task id*, a |
| 102 | number between 0 and ``num_processes``. Processes that exit |
| 103 | abnormally (due to a signal or non-zero exit status) are restarted |
| 104 | with the same id (up to ``max_restarts`` times). In the parent |
| 105 | process, ``fork_processes`` calls ``sys.exit(0)`` after all child |
| 106 | processes have exited normally. |
| 107 | |
| 108 | max_restarts defaults to 100. |
| 109 | |
| 110 | Availability: Unix |
| 111 | """ |
| 112 | if sys.platform == "win32": |
| 113 | # The exact form of this condition matters to mypy; it understands |
| 114 | # if but not assert in this context. |
| 115 | raise Exception("fork not available on windows") |
| 116 | if max_restarts is None: |
| 117 | max_restarts = 100 |
| 118 | |
| 119 | global _task_id |
| 120 | assert _task_id is None |
| 121 | if num_processes is None or num_processes <= 0: |
| 122 | num_processes = cpu_count() |
| 123 | gen_log.info("Starting %d processes", num_processes) |
| 124 | children = {} |
| 125 | |
| 126 | def start_child(i: int) -> Optional[int]: |
| 127 | pid = os.fork() |
| 128 | if pid == 0: |
| 129 | # child process |
| 130 | _reseed_random() |
| 131 | global _task_id |
| 132 | _task_id = i |
| 133 | return i |
| 134 | else: |
| 135 | children[pid] = i |
| 136 | return None |
| 137 | |
| 138 | for i in range(num_processes): |
| 139 | id = start_child(i) |