介绍
这篇文章将为大家详细讲解有关如何在Python中实现多进程,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
部署一个rpcServer
得到SimpleXMLRPCServer import SimpleXMLRPCServer def 添加(a ,, b):, return 才能;+ bserver =, SimpleXMLRPCServer ((“10.249.192.38",, 8000)) #这里不要用localhost,否则只有本机才能访问 server.register_function(添加) server.serve_forever ()
客户端:
得到xmlrpclib import 服务器 时间=Proxyserver ServerProxy (“http://localhost: 8000“) 试一试:ret =, server.add (90), print & # 39;结果:& # 39;,ret print & # 39; result 类型:& # 39;,类型(ret) 除了 例外,大敌;e: print “exception" e
其实还是很简单的。
然后再看了下python的多进程和多线程的方法,写了个例子,如下:
#=utf - 8编码 import 系统 import 操作系统 import 时间 import pdb import httplib import 线程 import 线程 constant_p =, 0, #创建全局变量,进程数 constant_s =, 0, #创建全局变量,线程数 时间=mutex_g threading.RLock(), #创建全局锁 def 运行(计数):#该函数创建3个线程,同时调用3个不同的函数 a 才能=1 b 才能=0 thread.start_new_thread才能(电平(a, b)) #这里传入的参数需要以元组的形式,跟空指针其实也差不多 thread.start_new_thread才能(test1 (a, b)) thread.start_new_thread才能(test2 (a, b)) def 电平(a, b): global mutex_g才能 global constant_s才能 时间=threadid 才能;thread.get_ident () mutex_g.acquire才能()#这里需要把线程数说锁起来,否则结果会被修改 时间=constant_s 才能;constant_s + 1 mutex_g.release才能() print 才能“thread  0,,以及从而threadid 是:% d" % (threadid) sys.exit才能(0) def test1 (a, b): global mutex_g才能 global constant_s才能 时间=threadid 才能;thread.get_ident () mutex_g.acquire才能() 时间=constant_s 才能;constant_s + 1 mutex_g.release才能() print 才能“thread  1,,以及从而threadid 是:% d" % (threadid) sys.exit才能(0) def test2 (a, b): global mutex_g才能 global constant_s才能 时间=threadid 才能;thread.get_ident () mutex_g.acquire才能() 时间=constant_s 才能;constant_s + 1 mutex_g.release才能() print 才能“thread 2,,以及从而threadid 是:% d" % (threadid) sys.exit才能(0) def my_fork (): global constant_p才能 pid 才能=,os.fork() #叉一个子进程,子进程的pid=0同时2个进程会执行my_fork()函数 if 才能;(pid ==, 0): #子进程执行到这个如果里面 ,,,constant_p =, constant_s + 1 ,,,(3)运行 ,,,time . sleep (5) ,,,print “total thread is % d" % constant_s #这个结果是3,因为子进程创建按了3个线程 elif 才能;(pid 在0):#父进程执行到这个如果里面 ,,,constant_p =, constant_s +, 1,运行(4) ,,,time . sleep (5) ,,,print “total thread is % d" % constant_s #这个结果也是3,因为该进程也创建了3个线程 其他的才能: ,,,print “fork error" ,,,sys.exit (0) print 才能“total  process is % d" % constant_p #该结果是1,因为2个进程只执行了一次 时间=constant_p 才能;constant_s + 1 sys.exit才能(0) if __name__ ==,“__main__": my_fork才能() #才能my_fork () # my_fork才能()
关于如何在Python中实现多进程就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。