Solved

while loop in threads - help please

Posted on 2004-09-28
10
177 Views
Last Modified: 2013-11-20
Hello,

In my project, I have to check if a particular condition is satisfied and take some action accordingly. Hence I have started a thread which continously checks for the condition as shown below:

UINT ThreadProc(LPVOID lp)
{
while(TRUE)
{
DWORD dwWaitResult = WaitForSingleObject(MonitorEvent,INFINITE);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
//do the required action and ...reset event
ResetEvent(MonitorEvent);
break;
}

}
MonitorEvent will be set in the part of the code where the required condition is met. Once the the event is fired, ThreadProc acts and does the required task and again has to wait till the event is fired again. This has to continue till application exists.

The result of the above code is that CPU time is getting consumed 100%.
Can anyone please suggest a better solution?
Thanks in anticipation of information.

madhavi.
0
Comment
Question by:l_madhavi
  • 6
  • 3
10 Comments
 
LVL 13

Expert Comment

by:SteH
ID: 12168342
I would suggest to use a Wait with a timeout. Check the result for timeout to continue. This way you can check for thread ending as well.

And to allow other processes/threads to get CPU cycles you can add to that loop a
Sleep (0); // perhaps something higher than 0 is better. This depends on thread priority in respect to other priorities.
0
 
LVL 13

Expert Comment

by:SteH
ID: 12168363
Sleep (0);
just gives CPU control to other threads withing your process or to other processes.

UINT ThreadProc(LPVOID lp)
{
   while(TRUE)
   {
      DWORD dwWaitResult = WaitForSingleObject(MonitorEvent,INFINITE);
      switch (dwWaitResult)
      {
      case WAIT_OBJECT_0:
         //do the required action and ...reset event
         ResetEvent(MonitorEvent);
         break;
      default: // ie. WAIT_TIMEOUT
      }
      // test for thread end!
      Sleep (0);
   }
}
0
 
LVL 13

Expert Comment

by:SteH
ID: 12168367
DWORD dwWaitResult = WaitForSingleObject(MonitorEvent,INFINITE);
should be
DWORD dwWaitResult = WaitForSingleObject(MonitorEvent,500); // test with other values than 0.5 s!
0
 

Author Comment

by:l_madhavi
ID: 12168506
Hi SteH
 

Thanks for your inputs.

My monitor thraed has to run continously and keep checking for the condition right from the application start to application exit.  

Hence I have to use INFINITE in  WaitForSingleObject. Though I used Sleep(0), the same is the case i.e CPU usage is shown as 100%. Can you please let me know how to proceed further?

Thanks
Madhavi
0
 
LVL 13

Expert Comment

by:SteH
ID: 12168524
Have you tried something like
Sleep (50);
or
Sleep (100);

How fast do you have to react on the event set? If I am not totally wrong you can allow a sleep before returning to WaitForSingleObject () and if the event is raised it will terminate immediatly with WAIT_OBJECT0 as result
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:l_madhavi
ID: 12168547
Hi SteH
 

Thanks for your inputs.

My monitor thraed has to run continously and keep checking for the condition right from the application start to application exit.  

Hence I have to use INFINITE in  WaitForSingleObject. If I used Sleep(10),  CPU usage is not 100%, but the application slows down that is the work that this thraed does slows down. Can you please let me know how to proceed further?

Thanks
Madhavi
0
 
LVL 13

Expert Comment

by:SteH
ID: 12168621
No, you don't have to use INFINITE under all circumstances. But to judge whether under your conditions you need it I need more info:
How often does this event occur per second?
How long may your thread not respond to it?
How important is that CPU usage is below 100%?
What is the thread priority and what the base priority of the app?
Is it a background application or run in foreground always?
Does your OS give more CPU cycles to the topmost applications or to share it evenly among all aplications?
0
 

Author Comment

by:l_madhavi
ID: 12186866
Hi Steh,

Below are my answers
How often does this event occur per second?
How long may your thread not respond to it?
I have a monitor event which gets triggered very very fast. One thraed reads data from file which has say minimum 10,000 records, it reads each line, and triggers Monitor event which displays the line on UI. Hence as soon as a line is read from file, Moinitor event gets triggered. So I can say monitor event gets triggered 10,000 times if 10,000 lines are there in the file. During this raeding and displaying operation CPU usage is shown as 100%, after the reading of file is over, it is not 100%.
I have declared my monitor event as below first.

volatile HANDLE m_MonitorEvent;
m_MonitorEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
ResetEvent(m_MonitorEvent);

//This event is set in the part of code which triggers this event.
SetEvent(m_MonitorEvent);

//Thread function
BOOL b_EventRunning = TRUE;
UINT ThreadProc(LPVOID lpVoid)
{
while(b_EventRunning == TRUE)
{
DWORD dwWaitResult = WaitForSingleObject(m_MonitorEvent, INFINITE);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
//Do the work
ResetEvent(m_MonitorEvent);
break;

default:
Sleep(1);
break;
}
}//end of while
}//end of ThraedProc

How important is that CPU usage is below 100%?
very important

What is the thread priority and what the base priority of the app?
normal

Is it a background application or run in foreground always?
foreground

Does your OS give more CPU cycles to the topmost applications or to share it evenly among all aplications?
-

Please let me know your suggestions now.
0
 
LVL 13

Accepted Solution

by:
SteH earned 20 total points
ID: 12187576
According to MSDN the wait
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/waitforsingleobject.asp
should not consume any CPU cycles. So that part should not be the culprit!

From what you now told about the application I wondow how the display thread gets the data of the line read?
0
 

Expert Comment

by:curero
ID: 12477294
 I think your code is wrong (but maybe you didn't give all the information on purpose): the file reader thread doesn't wait anywhere for the UI thread to complete its task. Exemple: thread 1 reads one line, triggers the event, thread 2 begins its work, thread 1 reads another line and signals the event, thread 2 finishes its work for the first line, but misses the second one as it resets the event. The solution is to use a mutex: each thread wait for the other one to complete the task. If you want to have the threads working independently you must find a way to store the lines given by the reader thread (in theory the reader might read all the 10.000 lines before the UI thread finishes one line).
  Sorry if I misunderstood the problem.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
Introduction: Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions. Continuing from the tenth article about sudoku.   Last article we worked with a modal dialog to help maintain informat…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now