Tornado和multiprocessing和fork

import tornado
import tornado.web
import os
import socket
import multiprocessing
import time

l = multiprocessing.Manager().list()

port = 8888

class IndexHandler(tornado.web.RequestHandler):
	def initialize(self,child_pid):
		self.child_pid = child_pid
	def get(self):
		global l
		s='hello client, child pid = %d'%self.child_pid
		self.write(s)
		print(l)

def server(child_pid):
	sockets = tornado.netutil.bind_sockets(port,family = socket.AF_INET)
	app = tornado.web.Application([(r"/", IndexHandler,{'child_pid':child_pid}),])
	httpd = tornado.httpserver.HTTPServer(app)
	httpd.add_sockets(sockets)
	tornado.ioloop.IOLoop.current().start()

def child_process():
	global l
	print(os.getpid())
	while True:
		l.append(os.getpid())
		time.sleep(10)
		pass
	pass
def main():
	pid = os.fork()
	if pid == 0:
		child_process()
	else:
		server(pid)

if __name__ == '__main__':
	main()

1、原本是通过tornado建立服务器,然后接收数据,交给另一个进程处理。用multiprocessing建立进程的话,主进程必须得join,因为全局进程共享变量l会因为主进程的结束而结束。现在用了fork(),tornado作为主进程,另一个程序作为子进程。

2、tornado中,可以通过tornado.web.Application([(r"/", IndexHandler,{'child_pid':child_pid}),]),以及def initialize(self,child_pid),进行传参数,例子中就是传递子进程的pid给tornado,这样,tornado就可以通过psutil库里的相关函数对子进程唤醒或阻塞。

3、fork后,全局进程共享变量l,并没有拷贝一份,应该是进程变量不会受到影响吧。

猜你喜欢

转载自blog.csdn.net/ZRXSLYG/article/details/84952709