简体   繁体   中英

Take multiple inputs simultaneously from console python

I am working on elevator program. The elevator should stop when someone press button in between.

eg: If the elevator goes to 11th floor and in between someone presses 3rd floor then it should stop.

I tried the program using multi-threading and it works like :

    while(True):
        t1= threading.Thread(target=get_input, name='t1')
        t2= threading.Thread(target=traverse, name='t2')
        t1.start()
        time.sleep(5)
        traverse()
        t2.start()

where traverse function moves elevator to desired floor.

Inshort the idea I implemented is 1 thread takes input and other thread moves elevator at a time. But is there any other way to do instead of threads (though this solution works)?

You can rewrite it without Threading in some scenarios, however you haven't mentioned how are you getting user input. are you getting from socket? or from another other custom protocol etc. So here i am providing some scenarios and solutions which i think can work.

  1. From Socket : Just make other get_input and traverse coroutines and use asyncio.gather at the end.
  2. From Console : we then you can use asyncio alternatives for common operations like input etc for example check this library https://github.com/vxgmichel/aioconsole . and use asyncio.gather/wait as mentioned above.

If above 2 solutions are not appropriate for your use case then you can create a state machine if traverse is non blocking and doesn't do much work. if traverse do more than trivial amount of work then than this solution is not appropriate because it might block program in single thread for long time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM