Domanda

I have a function which has the same interface as Python's input builtin, but it works in a client-server environment. When it's called, the function, which runs in the server, sends a message to the client, asking it to get some input from the user. The user enters some stuff, or dismisses the prompt, and the result is passed back to the server, which passes it to the function. The function then returns the result.

The function must work like Python's input [that's the spec], so it must block until it has the result.

This is all working, but it uses a busy loop, which, in practice, could easily be spinning for many minutes. Currently, the function tells the client to get the input, passing an id. The client returns the result with the id. The server puts the result in a dictionary, with the id as the key. The function basically waits for that key to exist.

def input():

    '''simplified example'''

    key = unique_key()
    tell_client_to_get_input(key)
    while key not in dictionary: pass
    return dictionary.pop(pin)

Using a callback would be the normal way to go, but the input function must block until the result is available, so I can't see how that could work. The spec can't change, as Python will be using the new input function for stuff like help and pdb, which provide their own little REPLs.

I have a lot of flexibility in terms of how everything works overall, but just can't budge on the function acting exactly like Python's.

Is there any way to return the result as soon as it's available, without the busy loop?

È stato utile?

Soluzione

You want a semaphore.

def input():
    make_network_call()
    sem.acquire()
    return shared_return_value

def callback():
    shared_return_value = whatever
    sem.release()

This makes input() block on the acquire() line until release() is called in the callback. The caller to input() isn't aware a callback was involved. Make sure to initialize the semaphore with a value of zero.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top