假设您有1000个客户端连接到一台扭曲的服务器。这些客户端不断地轮询更新(或者只是通过WebSocket之类的东西持久地连接)。服务器的工作是遍历所有1000个,检查其中哪些有更新,然后在它们到来时将它们发送出去。
有没有办法让它,在Twisted中,我可以在4个线程中运行250 (或者进一步划分它)?Twisted如何决定一次运行多少个任务?我可以连续检查250,甚至不时地改变分布吗?
这是我想象的一个非常简单的版本,尽管我不知道这在Twisted中是什么样子:
class Server:
queues = [["250 clients"], ["250 clients"], ["250 clients"], ["250 clients"]]
@classmethod
def run_server(cls):
for i in xrange(len(cls.queues)):
# this would run in its own thread
cls.continuously_check_for_updates(cls.queues[i])
# server mainloop
while True:
if get_client_connection():
store_client_in_queue()
distribute_client_queues()
@classmethod
def continuously_check_for_updates(cls, queue):
i = 0
while True:
if i >= len(queue):
i = 0
client = queue[i]
if check_for_updates(client):
report_update(client)
i += 1我很感谢你的见解和建议。谢谢。
发布于 2014-03-30 22:02:35
不是的。Python一次只执行一个线程(忽略一些不相关的细节)。没有理由使用线程来解决这个问题。
相反,您应该使用事件驱动的方法,在这种方法中,您不必不断地检查一千种不同的数据结构。相反,应在发生相关更改时采取行动。
例如,不要编写这样的程序:
def addSomeData(data):
someList.append(data)
def checkForData():
if someList:
return someList.pop(0)
return None
while True:
data = checkForData()
if data is not None:
processData(data)取而代之的是编写这样的程序:
def addSomeData(data):
processData(data)它简单得多,效率也更高。
https://stackoverflow.com/questions/22740191
复制相似问题