Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "while (true)" usually used for a permanent thread?

I'm relatively new to coding; most of my "work" has been just simple GUI apps that only function for one thing, so I haven't had to thread much.

Anyway, one thing I'm wondering about threading is if you want to keep a thread alive forever to do whatever job it's doing (processing, waiting for input, whatever), is it normal to format it like so:

while (true) {
    // do stuff
    Thread.Sleep(1000);
}

(or something along those lines)...? Or is this not safe and should it be avoided if possible?

like image 241
Corey Avatar asked Aug 15 '09 11:08

Corey


People also ask

Do threads end automatically?

A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.

How do you know when a thread has finished?

You can interrogate the thread instance with getState() which returns an instance of Thread. State enumeration with one of the following values: * NEW A thread that has not yet started is in this state. * RUNNABLE A thread executing in the Java virtual machine is in this state.


2 Answers

Yep, that's what you do.

But typically it's like:

bool keepRunning = true;

...

while(keepRunning){
}

Because sometimes you may like to have someone/something else to have the ability to stop you.

like image 81
Noon Silk Avatar answered Oct 25 '22 07:10

Noon Silk


To elaborate a bit more, if a thread is sleeping, when the OS comes along to activate the thread, it will just check to see if it's still sleeping and if so, then just yield its timeslice.

If you leave out the Sleep and do something like

while (true)
{
    if (workAvailable)
        {
        doWork();       
        }
}

then even if workAvailable is false it will keep spinning until the OS stops it, taking up its entire slice doing nothing. Obviously that's a little more inefficient.

You can get even more complex as needed with mutexes, semaphores and whatnot, as mentioned above, but things get complex quickly with those, so you might want to use them to solve a particular problem.

like image 4
Jason Avatar answered Oct 25 '22 09:10

Jason