Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is this while loop causing 100% cpu

Tags:

ios

iphone

I have a strange situation where a while loop is causing my cpu usage to go to between 90 and 100%. The cpu stays this high. If I comment out the while loop the cpu remains normal.

Whats going wrong here?

I've put in a breakpoint and the while loop definitely does exit.

[self performSelectorInBackground:@selector(checkstate:) withObject:padid];



-(void)checkstate:(PadIDSIdentifier*)pids
    {

        int pid=0;
        int cid=0;
        pid=pids.padid;
        cid=pids.channelid;


        NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];


        while (change==NO) 
        {

         // wait for the condition I want
         change=YES;




        }



        [pool release];

    }
like image 856
dubbeat Avatar asked Sep 03 '25 14:09

dubbeat


1 Answers

You're eating up the CPU in that loop. What you need to do is let the OS wait for you (which sets the wait process on low-priority so it occurs in idle time).

How you do that in Windows is WaitForSingleObject. How you do that on iPhone is with NSCondition.

Here is link: How do I use NSConditionLock? Or NSCondition

Basically, the NSCondition is signaled by the other thread, allowing your thread to resume processing.

like image 137
Lee Louviere Avatar answered Sep 05 '25 08:09

Lee Louviere