I am told by my mentor that it's a bad practice to use sleep in a multithreaded program.
I would push back against that blanket statement.
An alternative to using sleep()
as a means to make something happen at a certain time is
to submit a task to a timer. If you have a thread that does nothing else except sleep()
until a certain time and then
make some thing happen, then you could use a timer instead. And, if the thread
has a loop that makes the thing happen at periodic intervals, then you could use a recurring
timer event or, a timer event that re-submits itself.
If you have multiple threads, each of which exists only to make a certain thing happen at
a certain time, then you could streamline your program by using a
timer object instead. If your program has a GUI, then you're
probably using a GUI framework that already has a timer you can use,
so having even one "timing" thread probably wastes resources.
But, when you're talking about threads, your are talking about the architecture of your
program, and when you're talking about sleep()
, you are talking about a low-level
implementation detail. I am automatically suspicious of any hard rule of programming that
combines ideas from such widely different levels of design.
If I have a good reason for a thread to exist in my program*, then I will not hesitate to
write code that creates it, and if I have a good reason for one of my threads to sleep()
,**
then I will not hesitate to write that call.
* A good reason for a thread to exist would be to manage some stateful "process" that
progresses independently of other "processes" that happen inside the program.
** A good reason for a thread to sleep would be if there was some reason why a
pause was needed between two steps of a complex "process" that the thread manages.