Python在di上实现循环调度

2024-06-16 12:35:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个客户机-服务器应用程序,在这里客户机注册请求,并在稍后获得响应。在

对于快速插入,我使用defaultdict。在

{
    "john":   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
    "ram":    [2, 6],
    "bruce":  [1, 4, 5],
    "willam": [7, 1],
}

这个数据结构唯一易受影响的问题是"john"发出的请求太多,服务器无法公平及时地为其他客户机提供服务。在

所以我认为roundrobin可能会来拯救我,给我一个迭代器,它可以产生这样的客户机-

^{pr2}$

有谁能告诉我如何有效地实现这样一个迭代器?在

编辑:这就是我想到的。有没有人有更好的方法做事?在

def roundrobin(requests): 
    remaining = set(requests) 

    index = 0 
    while remaining: 
        up_next = set() 
        for key in remaining: 
            try: 
                print(key, requests[key][index])
            except IndexError: 
                continue 
            up_next.add(key) 
        remaining = up_next 
        index += 1 

它产生以下输出

ram 2
john 0
willam 7
bruce 1
bruce 4
ram 6
john 1
willam 1
john 2
bruce 5
john 3
john 4
john 5
john 6
john 7
john 8
john 9
john 10
john 11
john 12
john 13
john 14
john 15
john 16
john 17
john 18
john 19

Tags: key客户机indexjohnrequests服务器应用程序ramnext
2条回答

我觉得没有比这更好的了。在

def roundrobin2(requests):
    index = 0
    while requests:
        for key in list(requests):
            try:
                key, requests[key][index]
            except IndexError:
                del requests[key]
            else:
                index += 1

您可以为每个请求者创建一个bucket,并使用itertools.cycle循环使用,每次都弹出。在

import itertools

all_requests = {
    "john":   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
    "ram":    [2, 6],
    "bruce":  [1, 4, 5],
    "willam": [7, 1],
}

# handle requests:
for requester in itertools.cycle(all_requests):
    request, all_requests[requester] = all_requests[requester][0], all_requests[requester][1:]
    # Intuitively this seems faster than request = all_requests[requester].pop(0), but I could be wrong
    # you should profile this before using it in production code, or see my note below.

    response = handle_request(request)
    send_response(response)

请注意,我经常从这个列表的头部提取,所以您应该使用collections.deque来代替它,它具有从头部或尾部快速弹出和推送的功能。在

相关问题 更多 >