服务器:
import time
import random
from threading import Thread
from xmlrpc.server import SimpleXMLRPCServer
class ServerThread(Thread):
def __init__(self, server_addr):
┆ Thread.__init__(self)
┆ self.server = SimpleXMLRPCServer(server_addr)
┆ self.server.register_function(sleep, 'sleep')
def run(self):
┆ self.server.serve_forever()
# sleep for random number of seconds
def sleep():
r = random.randint(2,10)
print('sleeping {} seconds'.format(r))
time.sleep(r)
return 'slept {} seconds, exiting'.format(r)
# run server
def run_server(host="localhost", port=8000):
server_addr = (host, port)
thread1 = ServerThread(server_addr)
thread1.start()
print("Server thread started. Testing server ...")
print('listening on {} port {}'.format(host, port))
if __name__ == '__main__':
run_server()
客户:
import xmlrpc.client
server = xmlrpc.client.ServerProxy("http://localhost:8000/", allow_none=True)
print(server.sleep())
print(server.sleep())
print(server.sleep())
print(server.sleep())
问题:
我不能创建多个ServerThread实例都监听同一个端口,抛出异常。
我希望看到所有 4 个线程并行执行。
我错过了什么?后面有关于 GIL 的讲座吗?