I have a function which spawns various types of threads, one of the thread types needs to be spawned every x seconds. I currently have it like this:
bool isTime( Time t )
{
return t >= now();
}
void spawner()
{
Time t = now();
while( 1 )
{
if( isTime( t ) )//is time is called in more than one place in the real function
{
//launchthread and recalculation of t only happens once in real function
launchthread()
t = now() + offset;
}
}
}
but I’m thinking of changing it to:
bool isTime()
{
static Time t = now();
if( t >= now() )
{
t = now() + offset;
return true;
}
return false;
}
void spawner()
{
while( 1 )
{
if( isTime() )
launchthread();
}
}
I think the second way is neater but I generally avoid statics in much the same way I avoid global data; anyone have any thoughts on the different styles?
Apart from the problem I cited in the comments to the question, you should avoid clever tricks like the plague. The first form (after fixing the bug) is cleaner and easier to understand. The second form, OTOH, confuses the reader by giving the impression that the assignment to
tand the testt >= now()happen immediately after each other, who, on realising that its static, then has to try to grok the algorithm a second time.Also, you can never reset the second function or use it from multiple threads.