c++ - Two Windows - one modified by thread random output -


i'am trying write code where, window divide 2 pieces , 1 of them modfied different thread, output seems random. ? upper piece of console should modified main, , lower thread k.

#include <stdio.h> #include <ncurses.h> #include <unistd.h> #include <thread> #define width 30 #define height 10   int startx = 0; int starty = 0; void kupa (int score_size, int parent_x, int parent_y) {     int = 0;     window *dupa = newwin(score_size, parent_x, parent_y - score_size, 0);     while(true)     {          i++;          mvwprintw(dupa, 0 , 0, "you chose choice %d choice string", i);         wrefresh(dupa);           sleep(5);         wclear(dupa);     }     delwin(dupa); } int main () {        int parent_x, parent_y;       int score_size =10;       int counter =0 ;       initscr();       noecho();       curs_set(false);       getmaxyx(stdscr, parent_y, parent_x);       window *field = newwin(parent_y - score_size, parent_x, 0, 0);       std::thread k (kupa, score_size, parent_x, parent_y);       while(true) {           mvwprintw(field, 0, counter, "field");           wrefresh(field);           sleep(5);           wclear(field);           counter++;       }       k.join();       delwin(field);       } 

the underlying curses/ncurses library not thread-safe (see example what meant “thread-safe” code? discusses term). in case of curses, means library's window structures such stdscr global variables not guarded mutexes or other methods. library has internal static data shared across windows. can reliable results multithreaded code using 1 of these strategies:

  • do all of window management (including input) within 1 thread
  • use mutexes, semaphores or whatever concurrency technique seems best manage separate threads "own" separate windows. succeed here, thread have own whole screen point curses library blocks while waiting input, until updates screen , resumes waiting input. harder sounds.

ncurses 5.7 , can compiled provide rudimentary support reentrant code , threaded applications. this, uses mutexes wrapped around static data, makes global variables "getter" functions, , adds functions explicitly pass screen pointer implied in many calls. more detail, see manual page.

some of ncurses' test-programs illustrate threading support (these programs in test subdirectory of sources):

  • ditto shows use_screen.
  • test_opaque execises "getters" window properties
  • rain shows use_window
  • worm shows use_window

Popular posts from this blog