我有一个应用程序,它实例化一次xmlrpclib.ServerProxy,然后将它传递给多个线程(web应用程序请求),这些线程都同时执行XML/RPC调用。这在python2.6中运行得很好。使用python2.7,一旦我们处于多线程环境中,我们就会得到很多错误(ResponseNotReady,CannotSendRequest)。
# This code works well in python 2.6, and breaks in python 2.7.
import xmlrpclib
import thread
proxy = xmlrpclib.ServerProxy("http://localhost:5000/")
def fetch_users():
print proxy.getUsers()
for _ in range(10):
thread.start_new_thread(fetch_users, ())
while(1):
pass这里有什么问题,是否有一种线程安全的方法来重用ServerProxy对象?
发布于 2014-08-28 12:38:24
我们发现了问题的原因:在python2.6中,每个XML/RPC方法调用都会创建一个TCP连接。另一方面,Python2.7为每个ServerProxy对象打开一个TCP连接,并保持其打开(带有支持keep-alive的服务器)。此外,类不是线程安全的,因此并发请求可能会相互干扰。
显然,2.6版本是线程安全的,因为TCP连接不被重用,所有特定于连接的数据似乎都保存在非共享堆栈变量中。
因此,可能的解决办法是:
ServerProxy对象(并隐含地打开一个TCP连接)ServerProxy对象的访问发布于 2014-08-27 17:11:37
大多数代码不是线程安全。但是,我不知道为什么代码会在2.6中工作,但在2.7中会引发错误。
下面是关于这个问题的另一个看法:
threading模块。join()编辑,以确保它们都完成了。来源
import xmlrpclib
import threading
def fetch_users():
proxy = xmlrpclib.ServerProxy("http://localhost:5000/")
print proxy.getUsers()
for _ in range(10):
threading.Thread(target=fetch_users, args=()).start()
# wait for all threads to exit
for th in threading.enumerate():
th.join()https://stackoverflow.com/questions/25522228
复制相似问题