国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現的多進程和多線程功能示例

2020-02-15 21:33:41
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現的多進程和多線程功能。分享給大家供大家參考,具體如下:

聽了朋友說起,他們目前開發的測試框架,用python實現的分布式系統。雖然python的執行效率沒有c和c++那么高,但是依靠集群的力量,產生的壓力很是牛逼啊。

了解了下大概的方式就是

1、有臺主控機,負責調度,比如執行的參數等

2、有n多臺執行機,每個執行機上部署一個python的xmlRPC server,主控機調用rpccall,然后執行機執行。rpccall里面會fork一些進程,每個進程再創建一些線程,去調用測試方法。這樣,擴展性就很好了。

對于python的rpc call,之前也沒有接觸過,不是很了解,google了一下,發現很簡單,拿了個網上的例子,如下,先部署一個rpcServer

from SimpleXMLRPCServer import SimpleXMLRPCServerdef add(a , b):   return a+bserver = SimpleXMLRPCServer(("10.249.192.38", 8000))#這里不要用localhost,否則只有本機才能訪問server.register_function(add)server.serve_forever()

客戶端:

from xmlrpclib import ServerProxyserver = 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-8import sysimport osimport timeimport pdbimport httplibimport threadimport threadingconstant_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()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁化县| 邵武市| 桂林市| 洪洞县| 安丘市| 永昌县| 江津市| 巴里| 界首市| 建平县| 上犹县| 上林县| 青州市| 乌拉特中旗| 临潭县| 司法| 柏乡县| 平昌县| 漳浦县| 威远县| 通许县| 隆德县| 白城市| 文登市| 抚松县| 新建县| 丰都县| 江北区| 保定市| 洛浦县| 西昌市| 泰和县| 庄河市| 牙克石市| 大同县| 九龙县| 新津县| 吴旗县| 巴里| 象州县| 永靖县|