Python分布式测试框架:多进程多线程与XML-RPC实现详解
本文介绍基于Python构建分布式测试框架的方案,利用主控机调度与执行机RPC调用实现扩展性。通过SimpleXMLRPCServer部署服务,结合多进程(fork)与多线程技术,在多个节点上并行执行测试任务,有效弥补Python执行效率的不足,实现高并发压力测试。
本文通过具体实例,详细解析了Python中多进程与多线程功能的实现方法,供读者参考学习。
据朋友反馈,其团队目前开发的测试框架采用Python构建分布式系统。尽管Python的执行效率不及C和C++,但借助集群的协同力量,其产生的压力测试效果依然非常显著。
其核心架构大致如下:
1、设置一台主控机,负责整体任务调度及参数配置。
2、配置多台执行机,每台执行机上部署一个Python XML-RPC Server。主控机通过调用RPC接口触发任务,执行机接收到请求后,会fork出多个子进程,每个子进程再创建若干线程来调用具体的测试方法。这种架构具有良好的扩展性。
此前我对Python的RPC调用接触较少,经查阅资料发现其实现相当简单。以下是一个网络示例,首先展示如何部署一个RPC Server:
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的其他技术细节感兴趣,可参考本站相关专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。
希望本文的内容能对各位的Python程序设计工作提供有益帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









