printf Interrupts gets() or cin C++ (Console App)

Started by
3 comments, last by the_edd 14 years, 5 months ago
I made a server with the console and I was wondering if I can have it so 'gets()' or 'cin' won't get canceled if printf on a another thread gets called if people are sending messages to that user. It gets annoying if printf gets called after or on 'gets' and while your in the middle of typing it cancels that text and you have to start over again typing it out since printf got called on a second thread. Visual Studio C++ 2008 Console Winsock application
Check out my open source code projects/libraries! My Homepage You may learn something.
Advertisement
I can't replicate that with the following code:

#include <iostream>#include <string>#include <cstdio>#include <process.h>#include <windows.h>void threadfn(void *) {    Sleep(5000);    printf("threadfn!\n");}int main() {    _beginthread(threadfn, 0, 0);    std::string line;    std::getline(std::cin, line);    std::cout << line << std::endl;}


The "threadfn!" line does interrupt the typing line, but you can continue typing and hit ENTER, and the complete line entered is echoed back as expected.

Having the printf'd text merge with the keystrokes echoed in the console is normal behaviour, it's how plain consoles work.
If you have multiple threads accessing the console simultaneously, it'd be a good idea to make the console a mutually exclusive resource. In particular, write a wrapper that automatically locks and unlocks a mutex when accessing the console.

This will ensure that you get sane console behaviour regardless of what threads use the console; it should also ensure that you don't get any output spammed into the middle of an in-progress input.

Keep in mind though that mutexing your console may have unexpected consequences if you're relying on certain behaviours; frankly if you need anything much beyond "type and hit enter" then you should probably just write a full GUI for it.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Alright I'll have to agree with you guys on that. I was thinking I would end up making a GUI anyways for it to be safe then sorry, but thanks for your guys help!
Check out my open source code projects/libraries! My Homepage You may learn something.
If you're going to write a GUI anyway this doesn't apply, but you should never use gets(). It is fundamentally impossible to use safely.

This topic is closed to new replies.

Advertisement