How to run a loop while waiting for input?

Asked

Viewed 139 times

5

I want to know if you can run a repeat loop while waiting for an input type() and right after receiving the loop input for or while starts processing it immediately.

something like:

imputs = []
parar = false
def faca_algo(i):
    #fazendo algo


inputs.append(input("diga algo: ") # <--- essa linha permaneçe ativa

while not parar: #    <---- esse loop continua sendo executado
    faca_algo(inputs)
  • Could you be more specific? I have not understood what you want. Provide examples help as well.

  • I edited the question.

  • 1

    If this "something" you want to do is independent of the typed content, just create a new one thread and run it parallel to the thread reading the terminal. Have you tried something like? This other article may also be useful.

  • is just the opposite, the function receives the new parameters and processes them constantly, never stopping, while the user type new entries.

  • ah, ok. But I could have made it more clear in the question. :)

1 answer

4


Yes it is possible, but not with a single Thread, whereas programmes are sequence of instructions.

If I understand what you want, this is a simpler kind of problem Produtor/Consumidor (because I don’t think you have memory limitation). You will need to work with at least two threads and a shared memory area(a vetor, or lista, etc.[I will treat here as lista]) between the two threads.

While the thread produtora reads the data from the terminal and stores it in the lista to thread consumidora removes the next element from the list and performs the desired processing.

But working with shared memory areas brings some problems like, in case of a thread consumidora try to catch an element and the lista is empty. To solve this problem you will have to use semáforos, locks and etc.

For further study I suggest reading these articles.

This here better understanding of the problem of Producer and Consumer

https://ces33.blogspot.com.br/2009/05/o-problema-do-jantardos-filosofos-com.html

This one for python thread synchronization mechanisms

https://tibugs.wordpress.com/2014/06/11/python-compartilhando-recursos-e-sincronizando-threads-parte-1/

  • 1

    That’s what it was! I have no memory limitation, actually the idea is that the consumer access any item without removing it and if you need it can access again, nor come to mind, use two threads kk.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.