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

后端 未结 6 1162
温柔的废话
温柔的废话 2021-02-04 07:18

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\

6条回答
  •  清歌不尽
    2021-02-04 08:13

    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.

提交回复
热议问题