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

I'm trying to write code where the screen is divided into two windows and one of them is modified by a different thread, but output seems to be very random. Could anyone help? Upper piece of console should be modified by main, and lower by 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 i = 0;
WINDOW *dupa = newwin(score_size, parent_x, parent_y - score_size, 0);
while(true)
{
i++;
mvwprintw(dupa, 0 , 0, "You chose choice %d with 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 is not thread-safe (see for example What is meant by “thread-safe” code? which discusses the term). In the case of curses, this means that the library's WINDOW structures such as stdscr are global variables which are not guarded by mutexes or other methods. The library also has internal static data which is shared across windows. You can only get reliable results for multithreaded code using one of these strategies:
do all of the window management (including input) within one thread
use mutexes, semaphores or whatever concurrency technique seems best to manage separate threads which "own" separate windows. To succeed here, a thread would have to own the whole screen from the point where the curses library blocks while waiting for input, until it updates the screen and resumes waiting for input. That is harder than it sounds.
ncurses 5.7 and up can be compiled to provide rudimentary support for reentrant code and some threaded applications. To do this, it uses mutexes wrapped around its static data, makes the global variables into "getter" functions, and adds functions which explicitly pass the SCREEN pointer which is implied in many calls. For more detail, see the manual page.
Some of ncurses' test-programs illustrate the threading support (these are programs in the test subdirectory of the sources):
ditto shows use_screen.
test_opaque execises the "getters" for WINDOW properties
rain shows use_window
worm shows use_window

I am not sure what you want to do but this behaviour is quite normal. The thread that is active writes to the window and when the system makes a task switch the other thread writes to the window. Normal behaviour is to use only one thread that writes to the window. Other threads are supposed to do only some work.
Anyway, if you are using more than one thread you have to synchronize them using events, mutexes, queues, semaphores or other methods.

Related

recursive threading with C++ gives a Resource temporarily unavailable

So I'm trying to create a program that implements a function that generates a random number (n) and based on n, creates n threads. The main thread is responsible to print the minimum and maximum of the leafs. The depth of hierarchy with the Main thread is 3.
I have written the code below:
#include <iostream>
#include <thread>
#include <time.h>
#include <string>
#include <sstream>
using namespace std;
// a structure to keep the needed information of each thread
struct ThreadInfo
{
long randomN;
int level;
bool run;
int maxOfVals;
double minOfVals;
};
// The start address (function) of the threads
void ChildWork(void* a) {
ThreadInfo* info = (ThreadInfo*)a;
// Generate random value n
srand(time(NULL));
double n=rand()%6+1;
// initialize the thread info with n value
info->randomN=n;
info->maxOfVals=n;
info->minOfVals=n;
// the depth of recursion should not be more than 3
if(info->level > 3)
{
info->run = false;
}
// Create n threads and run them
ThreadInfo* childInfo = new ThreadInfo[(int)n];
for(int i = 0; i < n; i++)
{
childInfo[i].level = info->level + 1;
childInfo[i].run = true;
std::thread tt(ChildWork, &childInfo[i]) ;
tt.detach();
}
// checks if any child threads are working
bool anyRun = true;
while(anyRun)
{
anyRun = false;
for(int i = 0; i < n; i++)
{
anyRun = anyRun || childInfo[i].run;
}
}
// once all child threads are done, we find their max and min value
double maximum=1, minimum=6;
for( int i=0;i<n;i++)
{
// cout<<childInfo[i].maxOfVals<<endl;
if(childInfo[i].maxOfVals>=maximum)
maximum=childInfo[i].maxOfVals;
if(childInfo[i].minOfVals< minimum)
minimum=childInfo[i].minOfVals;
}
info->maxOfVals=maximum;
info->minOfVals=minimum;
// we set the info->run value to false, so that the parrent thread of this thread will know that it is done
info->run = false;
}
int main()
{
ThreadInfo info;
srand(time(NULL));
double n=rand()%6+1;
cout<<"n is: "<<n<<endl;
// initializing thread info
info.randomN=n;
info.maxOfVals=n;
info.minOfVals=n;
info.level = 1;
info.run = true;
std::thread t(ChildWork, &info) ;
t.join();
while(info.run);
info.maxOfVals= max<unsigned long>(info.randomN,info.maxOfVals);
info.minOfVals= min<unsigned long>(info.randomN,info.minOfVals);
cout << "Max is: " << info.maxOfVals <<" and Min is: "<<info.minOfVals;
}
The code compiles with no error, but when I execute it, it gives me this :
libc++abi.dylib: terminating with uncaught exception of type
std::__1::system_error: thread constructor failed: Resource
temporarily unavailable Abort trap: 6
You spawn too many threads. It looks a bit like a fork() bomb. Threads are a very heavy-weight system resource. Use them sparingly.
Within the function void Childwork I see two mistakes:
As someone already pointed out in the comments, you check the info level of a thread and then you go and create some more threads regardless of the previous check.
Within the for loop that spawns your new threads, you increment the info level right before you spawn the actual thread. However you increment a freshly created instance of ThreadInfo here ThreadInfo* childInfo = new ThreadInfo[(int)n]. All instances within childInfo hold a level of 0. Basically the level of each thread you spawn is 1.
In general avoid using threads to achieve concurrency for I/O bound operations (*). Just use threads to achieve concurrency for independent CPU bound operations. As a rule of thumb you never need more threads than you have CPU cores in your system (**). Having more does not improve concurrency and does not improve performance.
(*) You should always use direct function calls and an event based system to run pseudo concurrent I/O operations. You do not need any threading to do so. For example a TCP server does not need any threads to serve thousands of clients.
(**) This is the ideal case. In practice your software is composed of multiple parts, developed by independent developers and maintained in different modes, so it is ok to have some threads which could be theoretically avoided.
Multithreading is still rocket science in 2019. Especially in C++. Do not do it unless you know exactly what you are doing. Here is a good series of blog posts that handle threads.

Window Hangs And Freezes [SDL 2]

I have a text file full of information on where to place tiles in a game i'm making, the fastest way to access this information is with a for loop. But whenever i use the for loop to get through all the information it freezes the program for about 12 seconds, in those 12 i cant move the window, nothing on the renderer updates/is drawn, and then when i click on the window it breaks and says "window name (Not Responding)". I tried using a while loop but it still does the same thing.
How can i loop through bigger numbers (there are about 4,000 tiles in the level) without the program freezing/hanging on me? I'm just using SDL 2, no OpenGL involved.
int tiles = 4000;
int x[4000];
int y[4000];
tile obj[4000];
for(int i = 0; i < tiles; i++)
{
x[i] = txt.x;
y[i] = txt.y;
obj[i].Load(x[i], y[i]);
obj[i].Add();
SDL_RenderClear(ren);
LoadScreen();
SDL_RenderPresent(ren);
}
Thanks.
You need to create another thread.
It's good idea to wait for all data to load before starting game, so during load, you don't need to render anything. Even with this approach, it is better to use another thread and don't keep "UI Thread" busy. During load time your UI would be mostly disabled except a cancel button that will stop loading thread.
#include <process.h>
bool bReady;
void LoadTiles(void* pArg)
{
// Load Data here
*((int*)pArg) = 0;
///////////////////
bReady = true;
}
void main()
{
btnStart.SetEnabled(false);
bReady = false;
int iTarget;
uintptr_t hLoadingThread = _beginthread(LoadTiles, 0, &iTarget);
while (true) // usually you pick a message here
{
if (bReady)
btnStart.SetEnabled(true);
}
}
This is just a very simple example, multi-threading needs a lot of work and study!

How do Multi-process use the same ncurses screen?

I'm writing a c++ multi-process program with ncurses.
Each process is required to display something on the screen.
My Example code:
int main() {
initscr();
noecho();
curs_set(0);
int flag = fork();
if (flag == -1)
exit(1);
else if (flag == 0) {
WINDOW *win = newwin(4, 4, 0, 0);
int n = 0;
while (1) {
mvwprintw(win, 0, 0, "%d", n % 9);
wrefresh(win);
n = (n + 1) % 9;
sleep(1);
}
}
else {
WINDOW *win = newwin(4, 4, 8, 8);
int n = 0;
while (1) {
mvwprintw(win, 0, 0, "%d", n % 9);
wrefresh(win);
n = (n + 1) % 9;
sleep(1);
}
}
endwin();
return 0;
}
But it can only display one process's information on the screen.
How can I solve it?
I have hacked about something ugly that roughly works but shows what the problems are. I suspect a single window manager process which other processes communicate with would be better - or some horrible set of mutexes.
#include <stdlib.h>
#include <unistd.h>
#include <curses.h>
int main() {
initscr();
noecho();
curs_set(0);
WINDOW *win0 = newwin(4, 4, 0, 0);
WINDOW *win1 = newwin(4, 4, 8, 8);
int flag = fork();
if (flag == -1)
exit(1);
else if (flag == 0) {
int n = 0;
while (1) {
mvwprintw(win0, 0, 0, "%d", n % 9);
wrefresh(win0);
wrefresh(win1);
n = (n + 1) % 9;
sleep(1);
}
}
else {
int n = 0;
while (1) {
mvwprintw(win1, 0, 0, "%d", n % 9);
wrefresh(win1);
wrefresh(win0);
n = (n + 1) % 9;
sleep(1);
}
}
endwin();
return 0;
}
The example creates two 4x4 windows, with the second offset to 8,8. So they have no lines in common.
Since you're using fork (rather than vfork), the two processes should have separate address spaces, and there should be no way for one process to refresh a window which is modified in the other process. In some cases, developers have chosen to equate vfork and fork. With Linux, the vfork manual page comments:
Standard Description
(From POSIX.1) The vfork() function has the same effect as fork(2),
except that the behavior is undefined if the process created by vfork()
either modifies any data other than a variable of type pid_t used to
store the return value from vfork(), or returns from the function in
which vfork() was called, or calls any other function before successfully calling _exit(2) or one of the exec(3) family of functions.
but goes on to say
The requirements put on vfork() by the standards are weaker than
those put on fork(2), so an implementation where the two are
synonymous is compliant. In particular, the programmer cannot rely
on the parent remaining blocked until the child either terminates or
calls execve(2), and cannot rely on any specific behavior with
respect to shared memory.
That weaker and compliant is a developer arguing that making the two functions similar doesn't really matter...
The fork manual page asserts that there are separate address spaces:
The child process and the parent process run in separate memory
spaces. At the time of fork() both memory spaces have the same
content. Memory writes, file mappings (mmap(2)), and unmappings
(munmap(2)) performed by one of the processes do not affect the
other.
but we're left with that ambiguity in the description of vfork. Your program may fail to update the window belonging to the parent process as part of this vfork behavior — and refreshing both windows in the suggested answer merely confirms that the fork function is vfork in disguise.
POSIX currently has no page for vfork. It had one here (the fork description is worth reading).
Either way, using vfork wouldn't actually improve things. If you have to work within the same address space, that's what threads are for. If you have to use separate processes, making one process update the screen and other process(es) communicate with pipes is what people actually do.
A commented suggested that fork is obsolete. POSIX has something different to say on that aspect. Quoting from the rationale for posix_spawn:
The posix_spawn() function and its close relation posix_spawnp() have been introduced to overcome the following perceived difficulties with fork(): the fork() function is difficult or impossible to implement without swapping or dynamic address translation.
Swapping is generally too slow for a realtime environment.
Dynamic address translation is not available everywhere that POSIX might be useful.
Processes are too useful to simply option out of POSIX whenever it must run without address translation or other MMU services.
Thus, POSIX needs process creation and file execution primitives that can be efficiently implemented without address translation or other MMU services.
The posix_spawn() function is implementable as a library routine, but both posix_spawn() and posix_spawnp() are designed as kernel operations. Also, although they may be an efficient replacement for many fork()/ exec pairs, their goal is to provide useful process creation primitives for systems that have difficulty with fork(), not to provide drop-in replacements for fork()/ exec.
Further reading:
what is the difference between fork() and vfork()?
The difference between fork(), vfork(), exec() and clone()
EWONTFIX - vfork considered dangerous

How do I check if my multi-threading program works properly in C++?

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#define MAX_THREADS 1
#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI printNumbe(LPVOID);
// We need an array of Handles to threads
HANDLE hThreads[MAX_THREADS];
//...an array of thread id's
DWORD id[MAX_THREADS];
//And a waiter
DWORD waiter;
DWORD WINAPI printNumber(LPVOID n)
{
int num = (int)n;
for (int i = 0; i <= num; i++)
{
cout << "Hey there!" << endl;
}
return (DWORD)n;
}
//get ready, because here's where all the REAL magic happens
int main(int argc, char* argv[])
{
int number;
cout << "Please enter a number:" << endl;
cin >> number;
//here is where we call the CreateThread Win32 API Function that actually
//creates and begins execution of thread
//please read your help files for what each parameter does on
//your Operating system.
//Here's some basics:
//Parameter 0: Lookup, 1: Stack Size, 2: The function to run with this thread, 3: Any parameter that you want to pass to thread
//function, 4: Lookup , 5: Once thread is created, an id is put in this variable passed in
hThreads[0] = CreateThread(NULL, 0, printNumber, (LPVOID)number, NULL, &id[0]);
//now that all three threads are created and running, we need to stop the primary thread
// which is this program itself - remember that once "main" returns, our program exits
//so that our threads have time to finish. To do this, we do what is called "Blocking"
//we're going to make main just stop and wait until all three threads are done
//this is done easily with the next line of code. please read the help file about the specific API call
//"WaitForMultipleObjects"
waiter = WaitForMultipleObjects(MAX_THREADS, hThreads, TRUE, INFINITE);
//after all three threads have finished their task, "main" resumes and we're now ready
//to close the handles of the threads. This is just a bit of clean up work.
//Use the CloseHandle (API) function to do this.
for (int i = 0; i < MAX_THREADS; i++)
{
CloseHandle(hThreads[i]);
}
system("PAUSE");
return 0;
}
Hi all. Recently I've started taking Operating System class at my college.
I got some chance to learn about threads and multi threads. My professor gave me a power point slide with some sample codes on how to start multi-threading program in C++.
So I have decided to use his code as the base and decided to tweak it a bit so that I can understand it better.
Please disregard all those comments I made (most of comments don't apply to this program, those comments were basically in the slide and I just left it there as a reference).
SO I've tweaked to produce "Hey there!" "x" times depends on what number the user inputs into "x". As you are seeing, I made it to print inside printNumber function (sorry about the name, since my main assignment is on printing prime numbers , so forgive me about that).
So the program runs fine and exactly produces "Hey there!" multiple times.
But here's the question. Since my professor wants me to use multi-threads, how do I verify myself in C++ that the program in running with a multi-thread?
This program seems like printing "Hey there!" in a row (just like under a single thread) and there's no way I can tell if multi-threading has been applied to the program or not.
Keep in mind that, I am not that familiar with those syntax and it's my first time using WINAPI in C++ as well as first time doing threading programming.
Thank you very much.
GetCurrentThreadId will return the unique id for the current thread, if you print this inside your threaded function and main you should find it returns different values.

critical section problem in Windows 7

Why does the code sample below cause one thread to execute way more than another but a mutex does not?
#include <windows.h>
#include <conio.h>
#include <process.h>
#include <iostream>
using namespace std;
typedef struct _THREAD_INFO_ {
COORD coord; // a structure containing x and y coordinates
INT threadNumber; // each thread has it's own number
INT count;
}THREAD_INFO, * PTHREAD_INFO;
void gotoxy(int x, int y);
BOOL g_bRun;
CRITICAL_SECTION g_cs;
unsigned __stdcall ThreadFunc( void* pArguments )
{
PTHREAD_INFO info = (PTHREAD_INFO)pArguments;
while(g_bRun)
{
EnterCriticalSection(&g_cs);
//if(TryEnterCriticalSection(&g_cs))
//{
gotoxy(info->coord.X, info->coord.Y);
cout << "T" << info->threadNumber << ": " << info->count;
info->count++;
LeaveCriticalSection(&g_cs);
//}
}
ExitThread(0);
return 0;
}
int main(void)
{
// OR unsigned int
unsigned int id0, id1; // a place to store the thread ID returned from CreateThread
HANDLE h0, h1; // handles to theads
THREAD_INFO tInfo[2]; // only one of these - not optimal!
g_bRun = TRUE;
ZeroMemory(&tInfo, sizeof(tInfo)); // win32 function - memset(&buffer, 0, sizeof(buffer))
InitializeCriticalSection(&g_cs);
// setup data for the first thread
tInfo[0].threadNumber = 1;
tInfo[0].coord.X = 0;
tInfo[0].coord.Y = 0;
h0 = (HANDLE)_beginthreadex(
NULL, // no security attributes
0, // defaut stack size
&ThreadFunc, // pointer to function
&tInfo[0], // each thread gets its own data to output
0, // 0 for running or CREATE_SUSPENDED
&id0 ); // return thread id - reused here
// setup data for the second thread
tInfo[1].threadNumber = 2;
tInfo[1].coord.X = 15;
tInfo[1].coord.Y = 0;
h1 = (HANDLE)_beginthreadex(
NULL, // no security attributes
0, // defaut stack size
&ThreadFunc, // pointer to function
&tInfo[1], // each thread gets its own data to output
0, // 0 for running or CREATE_SUSPENDED
&id1 ); // return thread id - reused here
_getch();
g_bRun = FALSE;
return 0;
}
void gotoxy(int x, int y) // x=column position and y=row position
{
HANDLE hdl;
COORD coords;
hdl = GetStdHandle(STD_OUTPUT_HANDLE);
coords.X = x;
coords.Y = y;
SetConsoleCursorPosition(hdl, coords);
}
That may not answer your question but the behavior of critical sections changed on Windows Server 2003 SP1 and later.
If you have bugs related to critical sections on Windows 7 that you can't reproduce on an XP machine you may be affected by that change.
My understanding is that on Windows XP critical sections used a FIFO based strategy that was fair for all threads while later versions use a new strategy aimed at reducing context switching between threads.
There's a short note about this on the MSDN page about critical sections
You may also want to check this forum post
Critical sections, like mutexes are designed to protect a shared resource against conflicting access (such as concurrent modification). Critical sections are not meant to replace thread priority.
You have artificially introduced a shared resource (the screen) and made it into a bottleneck. As a result, the critical section is highly contended. Since both threads have equal priority, that is no reason for Windows to prefer one thread over another. Reduction of context switches is a reason to pick one thread over another. As a result of that reduction, the utilization of the shared resource goes up. That is a good thing; it means that one thread will be finished a lot earlier and the other thread will finish a bit earlier.
To see the effect graphically, compare
A B A B A B A B A B
to
AAAAA BBBBB
The second sequence is shorter because there's only one switch from A to B.
In hand wavey terms:
CriticalSection is saying the thread wants control to do some things together.
Mutex is making a marker to show 'being busy' so others can wait and notifying of completion so somebody else can start. Somebody else already waiting for the mutex will grab it before you can start the loop again and get it back.
So what you are getting with CriticalSection is a failure to yield between loops. You might see a difference if you had Sleep(0); after LeaveCriticalSection
I can't say why you're observing this particular behavior, but it's probably to do with the specifics of the implementation of each mechanism. What I CAN say is that unlocking then immediately locking a mutex is a bad thing. You will observe odd behavior eventually.
From some MSDN docs (http://msdn.microsoft.com/en-us/library/ms682530.aspx):
Starting with Windows Server 2003 with Service Pack 1 (SP1), threads waiting on a critical section do not acquire the critical section on a first-come, first-serve basis. This change increases performance significantly for most code