温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Python中实现多进程

发布时间:2021-04-07 17:45:17 来源:亿速云 阅读:176 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关如何在Python中实现多进程,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

部署一个rpcServer

from SimpleXMLRPCServer import SimpleXMLRPCServer
def add(a , b): 
  return a+bserver = SimpleXMLRPCServer(("10.249.192.38", 8000))#这里不要用localhost,否则只有本机才能访问
server.register_function(add)
server.serve_forever()

客户端:

from xmlrpclib import Server
Proxyserver = ServerProxy("http://localhost:8000")
try: ret = server.add(30,90) print 'result:', ret print 'result type:', type(ret)
except
 Exception, e: print "exception",e

其实还是很简单的。

然后再看了下python的多进程和多线程的方法,写了个例子,如下:

#encoding=utf-8
import sys
import os
import time
import pdb
import httplib
import thread
import threading
constant_p = 0 #创建全局变量,进程数
constant_s = 0 #创建全局变量,线程数
mutex_g = threading.RLock() #创建全局锁
def run(count):#该函数创建3个线程,同时调用3个不同的函数
  a = 1
  b = 0
  thread.start_new_thread(test0,(a,b))#这里传入的参数需要以元组的形式,跟void指针其实也差不多
  thread.start_new_thread(test1,(a,b))
  thread.start_new_thread(test2,(a,b))
def test0(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 called,and the threadid is:%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 called,and the threadid is:%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 called,and the threadid is:%d"%(threadid)
  sys.exit(0)
def my_fork():
  global constant_p
  pid = os.fork()#fork一个子进程,子进程的pid=0同时2个进程会执行my_fork()函数
  if (pid == 0):#子进程执行到这个if里面
    constant_p = constant_s + 1
    run(3)
    time.sleep(5)
    print "total thread is %d"%constant_s#这个结果是3,因为子进程创建按了3个线程
  elif (pid >0):#父进程执行到这个if里面
    constant_p = constant_s + 1 run(4)
    time.sleep(5)
    print "total thread is %d"%constant_s#这个结果也是3,因为该进程也创建了3个线程
  else:
    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中实现多进程就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI