Non-blocking stdio

后端 未结 3 1573
小蘑菇
小蘑菇 2020-12-19 18:09

I\'m working on a program which will be taking in user input from the console as well as printfing out in a separate thread. I want to avoid situations where the user is hal

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 18:59

    Turning off echo or using non-blocking I/O isn't the answer, if I understand your question correctly. Rather, you want to prevent a background thread from interrupting a user input thread, right?

    For that, you'll need access to raw keypresses instead of line-buffered input. I don't know why you're allergic to ncurses or similar libraries; that's what they're for! I guess you could do it with termios or ioctl calls, if that's how you roll....

    But to solve your multi-threaded TTY output problem, you could do this:

    1) Create a mutex to control who can access the console

    In the background thread, to output a message:

    Grab the mutex; write the message; release the mutex; go back to sleep!

    In the user input thread:

    Grab the mutex when new input is detected. Keep exclusive access until the user hits enter, then release the mutex and give the background thread a chance to talk.

    Does that help?

提交回复
热议问题