c++ how to remotely call a console window within opengl program - c++

What I am trying to do is make a graphing calculator that takes certain character inputs to transform the graph, but in order to do that I need to be able to generate a console window within the program. Is there any way in c++ to do that?
using Dev C++

but in order to do that I need to be able to generate a console window
within the program [...]
If by that you mean:
takes certain character inputs
then no, you dont need to be able to generate a console window. This being titled opengl program, a better fitting solution is to register keyboard callbacks for the current window (see here under glutKeyboardFunc) and handle everything through there. Other callbacks, for mouse, etc. are documented there as well.
There's no problem downloading freeglut (preserves same API and extends GLUT) in case you're missing any header(s)/libraries. Using Dev C++ is not a limiting factor for doing so.

For the purpose that I've submitted, you don't need to call a console. If you don't want to use the glut method above, what you can do instead is use a few functions present in the windows.h header file to take inputs.
The best way to implement inputs without glut involves creating a thread in your program that takes the inputs, and modifies a few variables that the main thread can use. Lets take a simple program here as an example:
#include <windows.h>
#include <pthread.h>
//the thread that takes the inputs
void * takeInputs(void * outputVariable)
{
//casts the output type so the compiler won't complain about setting void* to something
char * output = (char*) outputVariable;
//generic loop to stay alive
while (1 == 1) {
//checks to see if the key is in the on state, by getting only the needed bit in the data.
//In this case, we're checking to see if the A key on the keyboard is pressed
//You can use different keys like the arrow keys, using VK_UP VK_RIGHT
if (GetAsyncKeyState('A') & 0x8000 != 0)
{
*output = 1;
}
//put a delay in here so that the input doesn't consume a lot of cpu power
Sleep(100);
}
pthread_exit(0);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
{
//DoUnimportantWindowsSetup
char option = 0;
pthread_t Inputs;
//order: pointer to handle, Pointer to thread output, pointer to function, pointer to input
pthread_create(&Inputs, NULL, takeInputs, &option);
//Do stuff
if (option == 1) doWorks();
else doNotWorks();
//Order: thread handle, pointer to variable that stores output
pthread_join(Inputs, NULL);
return 0;
}

Related

GetDlgItemText and Multithreading

So I have been trying to implement the concept of multithreading to an MFC application I am making. I used the method suggested here. It works fine but I am having an issue with using data given by the user while the thread is working.
I'll explain.
I am making a simple GUI to send and receive data over a serial port. So the data in IDC_SEND is user-input, and is then sent through the serial port. I am using the WINAPI definition of GetDlgItemText, but since the controlling function for AfxBeginThread is defined as a static function I cannot do this. So I tried ::GetDlgItemText, but that calls the CWnd definition which takes one or three or four(?) arguments.
So ::GetDlgItemText(IDC_SEND, CString text) doesn't work. This problem continues for SetDlgItemText too.
I have tried getting the data outside my controlling function, but since it is defined to return a UINT type, I cannot get the received data out.
The relevant code
void CCommTest2Dlg::OnButton()
{
THREADSTRUCT *_param = new THREADSTRUCT;
_param->_this = this;
AfxBeginThread (StartThread, _param);
}
UINT CCommTest2Dlg::StartThread(LPVOID param)
{
THREADSTRUCT* ts = (THREADSTRUCT*)param;
AfxMessageBox ("Thread is started!");
//Opened Serial Port
//Writing data from Editbox
CString text;
::GetDlgItemText(IDC_SEND,text);//********ERROR HERE!!
serial.Write(text);
//At Receiver port data is wriiten into CString a.
CString a;
::SetDlgItemText( IDC_RECV, a);//Apparently this calls the SetDlgItemText from the CWnd class, and not the Windows API that takes more than one argument.
AfxMessageBox ((LPCTSTR)a);//This works, but I need the data in the EditBox.
//Closing Ports
delete ts; //Edit 1
return 1;}
A few definitions:
static UINT StartThread (LPVOID param);
//structure for passing to the controlling function
typedef struct THREADSTRUCT
{
CCommTest2Dlg* _this;
} THREADSTRUCT;
UINT StartThread(void);
Any thoughts?
PS: Also Edit 1 at the end was added by me as I read that this implementation could result in memory leaks. Does it look like the addition might have fixed that?

linux c++ libev official example show redundant console behavior

I just tried the official example of libev, like below. After compiling and running, I see once I input anything from stdin, the event is triggered, no problem. But what I inputed is still treated as solid input and then appear on my console. My question is: is there a way to avoid this console input from being prompted to console, and just like libev to catch and store it?
Any way in libev can do this?
I paste the official example here:
// a single header file is required
#include <ev.h>
#include <stdio.h> // for puts
// every watcher type has its own typedef'd struct
// with the name ev_TYPE
ev_io stdin_watcher;
ev_timer timeout_watcher;
// all watcher callbacks have a similar signature
// this callback is called when data is readable on stdin
static void
stdin_cb (EV_P_ ev_io *w, int revents)
{
puts ("stdin ready");
// for one-shot events, one must manually stop the watcher
// with its corresponding stop function.
ev_io_stop (EV_A_ w);
// this causes all nested ev_run's to stop iterating
ev_break (EV_A_ EVBREAK_ALL);
}
// another callback, this time for a time-out
static void
timeout_cb (EV_P_ ev_timer *w, int revents)
{
puts ("timeout");
// this causes the innermost ev_run to stop iterating
ev_break (EV_A_ EVBREAK_ONE);
}
int
main (void)
{
// use the default event loop unless you have special needs
struct ev_loop *loop = EV_DEFAULT;
// initialise an io watcher, then start it
// this one will watch for stdin to become readable
ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
ev_io_start (loop, &stdin_watcher);
// initialise a timer watcher, then start it
// simple non-repeating 5.5 second timeout
ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
ev_timer_start (loop, &timeout_watcher);
// now wait for events to arrive
ev_run (loop, 0);
// break was called, so exit
return 0;
}
I assume you mean the echoing of what you write? It's the default behavior of terminal program. You can use termios functions and flags to disable echoing. Remember to enable it before exiting your program though.
In ev_io_init you are setting what your trigger will be. Instead of setting STDIN_FILENO you can choose to use a fd from a socket for example. Don't know if this is what you are looking for. Here you have an example of what I am saying.

If-else statements won't work

I am trying to make a communication between two simultaneously running threads
through a global variable.
char dir='w'; //global var
UINT EditDir ( LPVOID pParam);//accepts dir from user in a loop
UINT Move ( LPVOID pParam); //processes dir (its incomplete)
int main()
{
........
........
CWinThread* pThread1 = AfxBeginThread(EditDir,(LPVOID)NULL);
CWinThread* pThread2 = AfxBeginThread(Move,(LPVOID)NULL);
WaitForSingleObject(pThread1, INFINITE);
........
........
}
UINT EditDir(LPVOID pParam)
{
bool end=false;
while (!end)
{
::dir = getchar();
Sleep(10);
if (::dir=='q')end=true;//***************************************
}
return 0;
}
UINT Move ( LPVOID pParam)
{
//process dir in a loop
return 0;
}
The if statement in while loop doesn't work its like the compiler removes the line before compilation.
after I press q the loop should end but it keeps on going.
Where am I wrong ?
Lots of things can go wrong with that code.
Compiler might optimize it so that dir is stored in a register and not reflected to the other function.
Compiler or processor might reorder statements which would result in some strange behaviour.
Write aliasing (your code write to some other variable that happens to be next to dir, and the processor optimizes the write to work with a block, effectively overwriting dir).
Out of thin air results.
Hitting low level(L1) caches that hold different values.
and much more.
You need to use thread-safe constructs. Use at least std::atomic to prevent write aliasing and a couple of other compiler optimizations that are not thread-safe.
You can also add a mutex to protect access to the variable.
Probably the best set-up is if one thread reads the char from input and pushes a copy into a producer-consumer queue or communication channel that you get from a well tested and well maintained library.
Finally, I found the mistake........
CWinThread* pThread2 = AfxBeginThread(Move,(LPVOID)NULL);// #1
WaitForSingleObject(pThread1, INFINITE); // #2
pThread is an object of a class....... not a handle and
WaitForSingleObject(HANDLE hHandle,DWORD dwMilliSeconds)// needs a handle
so what we do in between line #1 and #2 is
HANDLE hThread;
hThread=pThread->m_hThread;
and pass hThread in WaitForSingleObject(...) and not pThread.

c++ winapi threads

These days I'm trying to learn more things about threads in windows. I thought about making this practical application:
Let's say there are several threads started when a button "Start" is pressed. Assume these threads are intensive (they keep running / have always something to work on).
This app would also have a "Stop" button. When this button is pressed all the threads should close in a nice way: free resources and abandon work and return the state they were before the "Start" button was pressed.
Another request of the app is that the functions runned by the threads shouldn't contain any instruction checking if the "Stop" button was pressed. The function running in the thread shouldn't care about the stop button.
Language: C++
OS: Windows
Problems:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
How should I construct the wrapper function so that I can stop the thread properly?
( without using TerminateThread or some other functions )
What if the programmer allocates some memory dynamically? How can I free it before closing
the thread?( note that when I press "Stop button" the thread is still processing data)
I though about overloading the new operator or just imposing the usage of a predefined
function to be used when allocating memory dynamically. This, however, means
that the programmer who uses this api is constrained and it's not what I want.
Thank you
Edit: Skeleton to describe the functionality I'd like to achieve.
struct wrapper_data
{
void* (*function)(LPVOID);
LPVOID *params;
};
/*
this function should make sure that the threads stop properly
( free memory allocated dynamically etc )
*/
void* WrapperFunc(LPVOID *arg)
{
wrapper_data *data = (wrapper_data*) arg;
// what to write here ?
// if i write this:
data->function(data->params);
// i cannot stop the function from executing
delete data;
}
// will have exactly the same arguments as CreateThread
MyCreateThread(..., function, params, ...)
{
// this should create a thread that runs the wrapper function
wrapper_data *data = new wrapper_data;
data->function = function;
data->params = params;
CreateThread(..., WrapperFunc, (LPVOID) wrapper_data, ...);
}
thread_function(LPVOID *data)
{
while(1)
{
//do stuff
}
}
// as you can see I want it to be completely invisible
// to the programmer who uses this
MyCreateThread(..., thread_function, (LPVOID) params,...);
One solution is to have some kind of signal that tells the threads to stop working. Often this can be a global boolean variable that is normally false but when set to true it tells the threads to stop. As for the cleaning up, do it when the threads main loop is done before returning from the thread.
I.e. something like this:
volatile bool gStopThreads = false; // Defaults to false, threads should not stop
void thread_function()
{
while (!gStopThreads)
{
// Do some stuff
}
// All processing done, clean up after my self here
}
As for the cleaning up bit, if you keep the data inside a struct or a class, you can forcibly kill them from outside the threads and just either delete the instances if you allocated them dynamically or let the system handle it if created e.g. on the stack or as global objects. Of course, all data your thread allocates (including files, sockets etc.) must be placed in this structure or class.
A way of keeping the stopping functionality in the wrapper, is to have the actual main loop in the wrapper, together with the check for the stop-signal. Then in the main loop just call a doStuff-like function that does the actual processing. However, if it contains operations that might take time, you end up with the first problem again.
See my answer to this similar question:
How do I guarantee fast shutdown of my win32 app?
Basically, you can use QueueUserAPC to queue a proc which throws an exception. The exception should bubble all the way up to a 'catch' in your thread proc.
As long as any libraries you're using are reasonably exception-aware and use RAII, this works remarkably well. I haven't successfully got this working with boost::threads however, as it's doesn't put suspended threads into an alertable wait state, so QueueUserAPC can't wake them.
If you don't want the "programmer" of the function that the thread will execute deal with the "stop" event, make the thread execute a function of "you" that deals with the "stop" event and when that event isn't signaled executes the "programmer" function...
In other words the "while(!event)" will be in a function that calls the "job" function.
Code Sample.
typedef void (*JobFunction)(LPVOID params); // The prototype of the function to execute inside the thread
struct structFunctionParams
{
int iCounter;
structFunctionParams()
{
iCounter = 0;
}
};
struct structJobParams
{
bool bStop;
JobFunction pFunction;
LPVOID pFunctionParams;
structJobParams()
{
bStop = false;
pFunction = NULL;
pFunctionParams = NULL;
}
};
DWORD WINAPI ThreadProcessJob(IN LPVOID pParams)
{
structJobParams* pJobParams = (structJobParams*)pParams;
while(!pJobParams->bStop)
{
// Execute the "programmer" function
pJobParams->pFunction(pJobParams->pFunctionParams);
}
return 0;
}
void ThreadFunction(LPVOID pParams)
{
// Do Something....
((structFunctionParams*)pParams)->iCounter ++;
}
int _tmain(int argc, _TCHAR* argv[])
{
structFunctionParams stFunctionParams;
structJobParams stJobParams;
stJobParams.pFunction = &ThreadFunction;
stJobParams.pFunctionParams = &stFunctionParams;
DWORD dwIdThread = 0;
HANDLE hThread = CreateThread(
NULL,
0,
ThreadProcessJob,
(LPVOID) &stJobParams, 0, &dwIdThread);
if(hThread)
{
// Give it 5 seconds to work
Sleep(5000);
stJobParams.bStop = true; // Signal to Stop
WaitForSingleObject(hThread, INFINITE); // Wait to finish
CloseHandle(hThread);
}
}

How to visualise a calculation running in another thread in real time with vtk

I would like to visualise a running calculation in another thread with the visualisation tool kit in real time. The calculation spits out a new set of values to be visualised each iteration and the graphical thread must some how know this and load the new values.
One way to do this would be to have the main thread poll the state of the calculation. Ideally I'd not like to do any polling but if there is no other way then I will.
The best way I can think of would be to have the the calculation thread push an event onto the main thread's event queue every iteration of the calculation which is then processes by the GUI. I'm not sure how to go about doing this, or if it can be done in a thread safe manner.
I'm using vtk in gcc/C++ on linux using pthreads.
Listen to the Modified event on the object you're interested in, in the main thread using a vtkCommand (or appropriate derived class). You can then update your renderer and associated classes when the callback occurs.
But many VTK classes aren't thread-safe. You'll need to pause updation while rendering occurs. Otherwise, it'll segfault while trying to read and write the same memory.
I think it is a standard way. Create separate thread for window handling (i.e. window messages processing), and sometime put data into window (i.e. update the image).
Similar procedure with MathGL looks like following (see How I can create FLTK/GLUT/Qt window in parallel with calculation?)
//-----------------------------------------------------------------------------
#include <mgl/mgl_fltk.h>
#include <pthread.h>
#include <unistd.h>
mglPoint pnt; // some global variable for changable data
//-----------------------------------------------------------------------------
int sample(mglGraph *gr, void *)
{
gr->Box(); gr->Line(mglPoint(),pnt,"Ar2"); // just draw a vector
return 0;
}
//-----------------------------------------------------------------------------
void *mgl_fltk_tmp(void *) { mglFlRun(); return 0; }
int main (int argc, char ** argv)
{
mglGraphFLTK gr;
gr.Window(argc,argv,sample,"test"); // create window
static pthread_t tmp;
pthread_create(&tmp, 0, mgl_fltk_tmp, 0);
pthread_detach(tmp); // run window handling in the separate thread
for(int i=0;i<10;i++) // do calculation
{
sleep(1); // which can be very long
pnt = mglPoint(2*mgl_rnd()-1,2*mgl_rnd()-1);
gr.Update(); // update window
}
return 0; // finish calculations and close the window
}
//-----------------------------------------------------------------------------