Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the lowest cpu consumption when having an infinite loop in a thread

1.I have some infinite loops how can I get the lowest cpu consumption? Should I use a delay?

2.If I have multiple threads running in my application and one of them is THREAD_PRIORITY_IDLE does it affect other threads?

My code is as this for every thread

procedure TMatchLanLon.Execute;
begin
 while not Terminated do
  begin
          //some code
          Sleep(1000);
  end;
end;
like image 724
opc0de Avatar asked Mar 16 '12 13:03

opc0de


1 Answers

Typically a thread should sleep until signalled, but not using Sleep or SleepEx.

You create an Event and Wait for it to be signalled,either using TEvent or direct to Win32 API with WaitForSingleObject.

Sleep causes so many problems, including what I call "Sleeping beauty" disease. THe whole rest of your application has terminated and shut down a few hundred microseconds ago, and your thread has slept for a "million years" in relative computer timing terms, and when it wakes up the rest of your application has long since terminated. The next thing your background thread is likely to do is access some object which it has a reference to, which was frozen, and then (if you're lucky) it will crash. Don't use Sleep in threads. Wait for events, or use some pre-built worker thread (like the OmniThreadLibrary one).

like image 183
Warren P Avatar answered Nov 12 '22 09:11

Warren P