tornado.process — 多进程实用工具¶
Utilities for working with multiple processes, including both forking the server into multiple processes and managing subprocesses.
-
tornado.process.fork_processes(num_processes, max_restarts=100)[source]¶ Starts multiple worker processes.
If
num_processesis None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. Ifnum_processesis given and > 0, we fork that specific number of sub-processes.Since we use processes and not threads, there is no shared memory between any server code.
Note that multiple processes are not compatible with the autoreload module (or the
autoreload=Trueoption totornado.web.Applicationwhich defaults to True whendebug=True). When using multiple processes, no IOLoops can be created or referenced until after the call tofork_processes.In each child process,
fork_processesreturns its task id, a number between 0 andnum_processes. Processes that exit abnormally (due to a signal or non-zero exit status) are restarted with the same id (up tomax_restartstimes). In the parent process,fork_processesreturns None if all child processes have exited normally, but will otherwise only exit by throwing an exception.
-
tornado.process.task_id()[source]¶ Returns the current task id, if any.
Returns None if this process was not created by
fork_processes.
-
class
tornado.process.Subprocess(*args, **kwargs)[source]¶ Wraps
subprocess.Popenwith IOStream support.The constructor is the same as
subprocess.Popenwith the following additions:stdin,stdout, andstderrmay have the valuetornado.process.Subprocess.STREAM, which will make the corresponding attribute of the resulting Subprocess aPipeIOStream.- A new keyword argument
io_loopmay be used to pass in an IOLoop.
Changed in version 4.1: The
io_loopargument is deprecated.-
set_exit_callback(callback)[source]¶ Runs
callbackwhen this process exits.The callback takes one argument, the return code of the process.
This method uses a
SIGCHLDhandler, which is a global setting and may conflict if you have other libraries trying to handle the same signal. If you are using more than oneIOLoopit may be necessary to callSubprocess.initializefirst to designate oneIOLoopto run the signal handlers.In many cases a close callback on the stdout or stderr streams can be used as an alternative to an exit callback if the signal handler is causing a problem.
-
classmethod
initialize(io_loop=None)[source]¶ Initializes the
SIGCHLDhandler.The signal handler is run on an
IOLoopto avoid locking issues. Note that theIOLoopused for signal handling need not be the same one used by individual Subprocess objects (as long as theIOLoopsare each running in separate threads).Changed in version 4.1: The
io_loopargument is deprecated.