Sign in to follow this  

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

This topic is 2956 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 2956 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this