This question already has an answer here:
How can I run 3 QProcess in background using the same executable
(1 answer)
Closed 5 years ago.
I'm programming with Qt (c++) but my issue is universal in programming (most probably).
To simplify things, the function GetInput(string input) continuously scans for new input.
Depending on the input, the program exits or calls a recursive function.
The problem is, the RecursiveFunc() function blocks the GetInput() function, thus making it impossible to get further input (making it impossible to exit). Basically, the RecursiveFunc() function will call itself over and over, so the GetInput function never returns, making it impossible to get any more input.
My Question: How does a function call a recursive function BUT STILL continuously run and return WHILE the recursion is running.
//needs to constantly scan for input
void GetInput(string input)
{
if (input == "exit")
{
//terminate program
//this point is never reached after calling RecursiveFunc()
}
else if (input == "program1")
{
//Code executions gets stuck here because of recursion
RecursiveFunc();
int i = 0; //this statement is never reached, for example
}
}
void RecursiveFunc()
{
//update some values
//do some more things
//sleep a little, then call the fuction again
RecursiveFunc()
}
I'm thinking, something similiar to a fire-and-forget mechanism would be needed, but I can't quite figure it out. I could probably use threads, but I'm trying to avoid that (as the program should stay as simple as possible). As stated, I'm using Qt. So, what options do I have? What's the best solution in terms of simplicity?
Threads, co-routines, message loops with timers.
Qt has a message loop; change architecture to use that is simplest.
Co-routines lack language support, but there are myriads of implementations people have hacked together.
Threading is complex to get right, but keeps each code looking mostly linear.
Conclusion: Rewrite your code to be message loop based. Instead of recursive and sleeping, post a delayed message to do work later.
All right,
I found a way to achieve what I wanted without any fancy message loops and without rewriting my whole code. Instead of calling RecursiveFunc() recursively, I'm now calling GetInput() recursively (with qobject meta calls).
Simplified, this is my hackerishy solution:
//needs to constantly scan for input
void GetInput(string input)
{
if (input == "x")
{
//terminate program
}
else if (input == "program1")
{
RecursiveFunc();
//sleep a little
GetInput(""); //calls GetInput() recursively
}
}
void RecursiveFunc()
{
//update some values
//do some more things
}
I'm not sure if this is a very good practice, but it works for now.
Related
I am relearning C++. I was quite a noob before but I am going over the basics again and hopefully going further. My main question is, at the end of the main loop, is there a way to call the function again instead of ending the programme by returning 0. So something along the line of:
........
return main;
}
The standard C++ says...
5.2.2.9 Recursive calls are permitted, except to the function named main
"The Standard" at https://isocpp.org/std/the-standard
You could certainly do something like this:
int main()
{
while(1==1) /* (1==1) is always true. */
{
/* Do the hokey pokey, turn yourself around, and do whatever else you feel like doing. */
}
/* The program will never reach this point unless you explicitly break out of the loop. */
return 0;
}
This will result in a program that just repeats over and over again until you kill it. This is, of course, bad style, but it will work if you just need to get something up and running quickly.
As Trevor Hickey mentions, you could call break from within the loop and break out.
I'm a game developer therefore performance is really important to me.
My simple question:
I have a lot of checks(button clicks,collisions,whatever) running per frame, but I don't want to put everything in one function, therefore I would split them into other functions and just call them:
void Tick()
{
//Check 1 ..... lots of code
//Check 2 ...... lots of code
//Check 3 ..... lots of code
}
to
void Tick()
{
funcCheck1();
funcCheck2();
funcCheck3();
}
void funcCheck1()
{
//check1 lots of code
}
void funcCheck2()
{
//check2 lots of code
}
void funcCheck3()
{
//check3 lots of code
}
Does the function call per frame has any performance impact?(not inlined)
Clearly the second version is much more readable.
If you don't pass any complex objects by value, the overhead of calling several functions instead of putting all code in one function should be negligible (e.g.
put function parameters on top of the stack, add space for the return type, jump to the beginning of the called function's code)
You cannot say for sure, specifically that the compiler could inline small function automatically. The only way to be sure is to use a profiler and compare the two scenarios.
The problem:
First off, this is a simplified example of my problem, and it is really part of a large framework already programmed by someone else in which i have to adapt my code into.
I have 3 functions. Two of the functions (function1 and function2) are being called by other parts of the program both asynchronously and synchronously.
My last function (function3) runs continuously, like a while loop, and the only thing it does is to fire an event code on each code iteration.
I only want this last function to run whenever one of the two other functions have completed an iteration/been called.
I can not change how/when they are called, i can only block the execution of the code and unblock it.
I am fairly new to c++ and i have tried solving this using a mutex, but i have had no luck.
I can add the code, but it really is just like i explained.
void function1(){ // this function is called by other parts of the program
//some code
}
void funtion2(){ //this function is also called by other parts of the program
//some other code
}
void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it
fireEvent();//fires an event to run some other code
}
So, function3 runs all the time unless blocked, and i would only like to run the function every time one of the other functions have had one run-through. Like i said before, i can not call function3 myself, i can only manipulate the code in the function.
What is the best way of going about this?
After intense googleing i have only come up with conditional variables, semaphore and mutex, but i don't know enough about them to know how i can implement it correctly.
Any help/input/tip is greatly appreciated.
A straigtforward way would be like this:
mutex g_mutex;
condition_variable g_cond;
bool flag = false;
void function1(){ // this function is called by other parts of the program
//some code
lock_guard<mutex> lock(g_mutex);
flag = true;
g_cond.notify_one();
}
void funtion2(){ //this function is also called by other parts of the program
//some other code
lock_guard<mutex> lock(g_mutex);
flag = true;
g_cond.notify_one();
}
void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it
{
unique_lock<mutex> lock(g_mutex);
g_cond.wait(lock, []{return flag;}); // wait here until func1 or func2 have been called
flag = false;
}
fireEvent();//fires an event to run some other code
}
int main() {
// your code goes here
return 0;
}
But this will block your function3 until one of the other twos are called. So it is a change of the behaviour and it adds additional lock contention.
I have a question about use of the goto statement in C++. I understand that this topic is controversial, and am not interested in any sweeping advice or arguments (I usually stray from using goto). Rather, I have a specific situation and want to understand whether my solution, which makes use of the goto statement, is a good one or not. I would not call myself new to C++, but would not classify myself as a professional-level programmer either. The part of the code which has generated my question spins in an infinite loop once started. The general flow of the thread in pseudocode is as follows:
void ControlLoop::main_loop()
{
InitializeAndCheckHardware(pHardware) //pHardware is a pointer given from outside
//The main loop
while (m_bIsRunning)
{
simulated_time += time_increment; //this will probably be += 0.001 seconds
ReadSensorData();
if (data_is_bad) {
m_bIsRunning = false;
goto loop_end;
}
ApplyFilterToData();
ComputeControllerOutput();
SendOutputToHardware();
ProcessPendingEvents();
while ( GetWallClockTime() < simulated_time ) {}
if ( end_condition_is_satisified ) m_bIsRunning = false;
}
loop_end:
DeInitializeHardware(pHardware);
}
The pHardware pointer is passed in from outside the ControlLoop object and has a polymorphic type, so it doesn't make much sense for me to make use of RAII and to create and destruct the hardware interface itself inside main_loop. I suppose I could have pHardware create a temporary object representing a sort of "session" or "use" of the hardware which could be automatically cleaned up at exit of main_loop, but I'm not sure whether that idea would make it clearer to somebody else what my intent is. There will only ever be three ways out of the loop: the first is if bad data is read from the external hardware; the second is if ProcessPendingEvents() indicates a user-initiated abort, which simply causes m_bIsRunning to become false; and the last is if the end-condition is satisfied at the bottom of the loop. I should maybe also note that main_loop could be started and finished multiple times over the life of the ControlLoop object, so it should exit cleanly with m_bIsRunning = false afterwards.
Also, I realize that I could use the break keyword here, but most of these pseudocode function calls inside main_loop are not really encapsulated as functions, simply because they would need to either have many arguments or they would all need access to member variables. Both of these cases would be more confusing, in my opinion, than simply leaving main_loop as a longer function, and because of the length of the big while loop, a statement like goto loop_end seems to read clearer to me.
Now for the question: Would this solution make you uncomfortable if you were to write it in your own code? It does feel a little wrong to me, but then I've never made use of the goto statement before in C++ code -- hence my request for help from experts. Are there any other basic ideas which I am missing that would make this code clearer?
Thanks.
Avoiding the use of goto is a pretty solid thing to do in object oriented development in general.
In your case, why not just use break to exit the loop?
while (true)
{
if (condition_is_met)
{
// cleanup
break;
}
}
As for your question: your use of goto would make me uncomfortable. The only reason that break is less readable is your admittance to not being a strong C++ developer. To any seasoned developer of a C-like language, break will both read better, as well as provide a cleaner solution than goto.
In particular, I simply do not agree that
if (something)
{
goto loop_end;
}
is more readable than
if (something)
{
break;
}
which literally says the same thing with built-in syntax.
With your one, singular condition which causes the loop to break early I would simply use a break. No need for a goto that's what break is for.
However, if any of those function calls can throw an exception or if you end up needing multiple breaks I would prefer an RAII style container, this is the exact sort of thing destructors are for. You always perform the call to DeInitializeHardware, so...
// todo: add error checking if needed
class HardwareWrapper {
public:
HardwareWrapper(Hardware *pH)
: _pHardware(pH) {
InitializeAndCheckHardware(_pHardware);
}
~HardwareWrapper() {
DeInitializeHardware(_pHardware);
}
const Hardware *getHardware() const {
return _pHardware;
}
const Hardware *operator->() const {
return _pHardware;
}
const Hardware& operator*() const {
return *_pHardware;
}
private:
Hardware *_pHardware;
// if you don't want to allow copies...
HardwareWrapper(const HardwareWrapper &other);
HardwareWrapper& operator=(const HardwareWrapper &other);
}
// ...
void ControlLoop::main_loop()
{
HardwareWrapper hw(pHardware);
// code
}
Now, no matter what happens, you will always call DeInitializeHardware when that function returns.
UPDATE
If your main concern is the while loop is too long, then you should aim at make it shorter, C++ is an OO language and OO is for split things to small pieces and component, even in general non-OO language we generally still think we should break a method/loop into small one and make it short easy for read. If a loop has 300 lines in it, no matter break/goto doesn't really save your time there isn't it?
UPDATE
I'm not against goto but I won't use it here as you do, I prefer just use break, generally to a developer that he saw a break there he know it means goto to the end of the while, and with that m_bIsRunning = false he can easily aware of that it's actually exit the loop within seconds. Yes a goto may save the time for seconds to understand it but it may also make people feel nervous about your code.
The thing I can imagine that I'm using a goto would be to exit a two level loop:
while(running)
{
...
while(runnning2)
{
if(bad_data)
{
goto loop_end;
}
}
...
}
loop_end:
Instead of using goto, you should use break; to escape loops.
There are several alternative to goto: break, continue and return depending on the situation.
However, you need to keep in mind that both break and continue are limited in that they only affect the most inner loop. return on the other hand is not affected by this limitation.
In general, if you use a goto to exit a particular scope, then you can refactor using another function and a return statement instead. It is likely that it will make the code easier to read as a bonus:
// Original
void foo() {
DoSetup();
while (...) {
for (;;) {
if () {
goto X;
}
}
}
label X: DoTearDown();
}
// Refactored
void foo_in() {
while (...) {
for (;;) {
if () {
return;
}
}
}
}
void foo() {
DoSetup();
foo_in();
DoTearDown();
}
Note: if your function body cannot fit comfortably on your screen, you are doing it wrong.
Goto is not good practice for exiting from loop when break is an option.
Also, in complex routines, it is good to have only one exit logic (with cleaning up) placed at the end. Goto is sometimes used to jump to the return logic.
Example from QEMU vmdk block driver:
static int vmdk_open(BlockDriverState *bs, int flags)
{
int ret;
BDRVVmdkState *s = bs->opaque;
if (vmdk_open_sparse(bs, bs->file, flags) == 0) {
s->desc_offset = 0x200;
} else {
ret = vmdk_open_desc_file(bs, flags, 0);
if (ret) {
goto fail;
}
}
/* try to open parent images, if exist */
ret = vmdk_parent_open(bs);
if (ret) {
goto fail;
}
s->parent_cid = vmdk_read_cid(bs, 1);
qemu_co_mutex_init(&s->lock);
/* Disable migration when VMDK images are used */
error_set(&s->migration_blocker,
QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
"vmdk", bs->device_name, "live migration");
migrate_add_blocker(s->migration_blocker);
return 0;
fail:
vmdk_free_extents(bs);
return ret;
}
I'm seeing loads of people suggesting break instead of goto. But break is no "better" (or "worse") than goto.
The inquisition against goto effectively started with Dijkstra's "Go To Considered Harmful" paper back in 1968, when spaghetti code was the rule and things like block-structured if and while statements were still considered cutting-edge. ALGOL 60 had them, but it was essentially a research language used by academics (cf. ML today); Fortran, one of the dominant languages at the time, would not get them for another 9 years!
The main points in Dijkstra's paper are:
Humans are good at spatial reasoning, and block-structured programs capitalise on that because program actions that occur near each other in time are described near each other in "space" (program code);
If you avoid goto in all its various forms, then it's possible to know things about the possible states of variables at each lexical position in the program. In particular, at the end of a while loop, you know that that loop's condition must be false. This is useful for debugging. (Dijkstra doesn't quite say this, but you can infer it.)
break, just like goto (and early returns, and exceptions...), reduces (1) and eliminates (2). Of course, using break often lets you avoid writing convoluted logic for the while condition, getting you a net gain in understandability -- and exactly the same applies for goto.
Having read a bit about function pointers and callbacks, I fail to understand the basic purpose of it. To me it just looks like instead of calling the function directly we use the pointer to that function to invoke it. Can anybody please explain me callbacks and function pointers? How come the callback takes place when we use function pointers, because it seems we just call a function through a pointer to it instead of calling directly?
Thanks
ps: There have been some questions asked here regarding callbacks and function pointers but they do not sufficiently explain my problem.
What is a Callbak function?
In simple terms, a Callback function is one that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when a operation(function) can take long time for execution and the caller of the function does not want to wait till the operation is complete, but does wish to be intimated of the outcome of the operation. Typically, Callback functions help implement such an asynchronous mechanism, wherein the caller registers to get inimated about the result of the time consuming processing and continuous other operations while at a later point of time, the caller gets informed of the result.
An practical example:
Windows event processing:
virtually all windows programs set up an event loop, that makes the program respond to particular events (eg button presses, selecting a check box, window getting focus) by calling a function. The handy thing is that the programmer can specify what function gets called when (say) a particular button is pressed, even though it is not possible to specify when the button will be pressed. The function that is called is referred to as a callback.
An source Code Illustration:
//warning: Mind compiled code, intended to illustrate the mechanism
#include <map>
typedef void (*Callback)();
std::map<int, Callback> callback_map;
void RegisterCallback(int event, Callback function)
{
callback_map[event] = function;
}
bool finished = false;
int GetNextEvent()
{
static int i = 0;
++i;
if (i == 5) finished = false;
}
void EventProcessor()
{
int event;
while (!finished)
{
event = GetNextEvent();
std::map<int, Callback>::const_iterator it = callback_map.find(event);
if (it != callback_map.end()) // if a callback is registered for event
{
Callback function = *it;
if (function)
{
(*function)();
}
else
{
std::cout << "No callback found\n";
}
}
}
}
void Cat()
{
std::cout << "Cat\n";
}
void Dog()
{
std::cout << "Dog\n";
}
void Bird()
{
std::cout << "Bird\n";
}
int main()
{
RegisterCallBack(1, Cat);
RegisterCallback(2, Dog);
RegisterCallback(3, Cat);
RegisterCallback(4, Bird);
RegisterCallback(5, Cat);
EventProcessor();
return 0;
}
The above would output the following:
Cat
Dog
Cat
Bird
Cat
Hope this helps!
Note: This is from one of my previous answers, here
One very striking reason for why we need function pointers is that they allow us to call a function that the author of the calling code (that's us) does not know! A call-back is a classic example; the author of qsort() doesn't know or care about how you compare elements, she just writes the generic algorithm, and it's up to you to provide the comparison function.
But for another important, widely used scenario, think about dynamic loading of libraries - by this I mean loading at run time. When you write your program, you have no idea which functions exist in some run-time loaded library. You might read a text string from the user input and then open a user-specified library and execute a user-specified function! The only way you could refer to such function is via a pointer.
Here's a simple example; I hope it convinces you that you could not do away with the pointers!
typedef int (*myfp)(); // function pointer type
const char * libname = get_library_name_from_user();
const char * funname = get_function_name_from_user();
void * libhandle = dlopen(libname, RTLD_NOW); // load the library
myfp fun = (myfp) dlsym(libhandle, funname); // get our mystery function...
const int result = myfp(); // ... and call the function
// -- we have no idea which one!
printf("Your function \"%s:%s\" returns %i.\n", libname, funname, result);
It's for decoupling. Look at sqlite3_exec() - it accepts a callback pointer that is invoked for each row retrieved. SQLite doesn't care of what your callback does, it only needs to know how to call it.
Now you don't need to recompile SQLite each time your callback changes. You may have SQLite compiled once and then just recompile your code and either relink statically or just restart and relink dynamically.
It also avoids name collision. If you have 2 libs, both do sorting and both expect you to define a function called sort_criteria that they can call, how would you sort 2 different objects types with the same function?
It would quickly get complicated following all the if's and switches in the sort_criteria function, with callbacks you can specify your own function (with their nice to interpret name) to those sort functions.