0

I'm coming from C and don't have too much programming knowledge, so bear with me if my idea is nonsense.

Right now, I'm trying to write a simple threaded application with double-buffered console output. I've got a thread which resets the cursor position, draws the buffer and then waits n milliseconds:

gotoxy(0, 0);
std::cout << *draw_buffer;
std::this_thread::sleep_for(std::chrono::milliseconds(33));

This works perfectly well. The buffer is filled independently by another thread and also causes no problems.

Now I want the user to be able to feed the application information. However, my drawing thread always puts the cursor back to the start, so the user input and the application output will interfere. I'm aware there are libraries like curses, but I'd prefer to write this myself, if possible. Unfortunately, I haven't found any solution to this. I guess there is no way to have two console cursors moving independently? How else could I approach this problem?

Julian B
  • 402
  • 1
  • 7
  • 15
  • I'm assuming you're programming on a Windows environment since you're using conio.h. Is that right? You said you prefer to "write this yourself" and avoid using the curses library if possible. I'm not sure what you mean by "yourself" as you're already use conio.h (which, btw, also won't be portable if that is what you're concerned about). Can you elaborate on what you mean by writing it yourself? – master_latch Jan 18 '14 at 16:40
  • I'm using windows.h and SetConsoleCursorPosition. The gotoxy(x, y) is only a wrapper function for this. – Julian B Jan 18 '14 at 16:44

1 Answers1

0

I think what you will need to do two things:

  • Create a mutex that controls which thread is writing to stdout.
  • Change the input mode so that when you invoke getchar, it returns immediately (rather than waiting for the user to press enter). You can then wait for the other thread to release the mutex, then move the cursor and echo the character the user pressed at the appropriate part of the screen.

You can change the input mode using tcsetattr, although this is from termios which is for *nix systems. Since you're using windows, this may not work for you unless you're using cygwin.

maybe check this out: What is the Windows equivalent to the capabilities defined in sys/select.h and termios.h

Community
  • 1
  • 1
master_latch
  • 434
  • 5
  • 12