Reputation: 3761
Im trying to run a function that will never end (until the program is killed)
How would i start such a function and be able to continue on past that function, because at the moment the program will not run past the never ending function.
Regards
Paul
Upvotes: 2
Views: 1167
Reputation: 45057
Executing "past" a never-ending function isn't possible (if it doesn't end, you can't move past it). I am assuming that you want to have some code running in a loop in the background while your program does something else.
You want something like this:
#include <pthread.h>
int endLoop;
void* backgroundLoop(void* arg) {
while (!endLoop) {
...
}
return NULL;
}
int main (int argc, char** argv) {
pthread_t thread;
int retval;
...
// Launch background thread
endLoop = 0;
retval = pthread_create(&thread, NULL, backgroundLoop, NULL);
// Continue with main function
...
// Force background loop to end
endLoop = 1;
}
If you are using pthreads, you can find more info here. If you are using some other thread library, the concept will be similar but the thread create/destroy functions may look different.
Upvotes: 1
Reputation: 27516
While I'd agree with everyone else that a thread is probably the easiest way to go, this scenario doesn't sound like something that should ever happen (at least not deliberately) - it sounds like this originates from a design problem.
Why do you need a function that will run forever? What does this function do? There may be a more appropriate programming model, such as a Windows service or a daemon process. Also, it's usually better to send the thread a signal that it's time to end, and have the thread do it's thing until it receives such a message (rather than just force-killing it when the app exits).
I don't know enough about what you're trying to do here, but I'd suggest examining your design and see if there's a better way.
Upvotes: 2
Reputation: 1682
An idea for a pseudo-thread based on a similar issue I needed to fix without threading (may or may not work for you):
Upvotes: -1
Reputation: 62333
Fire it off in a thread. It would still, however, be really sensible to allow the function to exit.
Upvotes: 1
Reputation: 38287
You'd need to start a new thread. A given thread can only execute one function at a time. So, if you want to have two separate functions executing at the same time, you need multiple threads. You'll need to look into multi-threaded programming. If you're on linux or another unix-based system, then the library to look at would be pthreads.
Upvotes: 11