1, simple can think of, write a while loop
while (TRUE) { }
However, this approach is flawed and will result in CPU consumption of 100% and two cores.
This approach is not elegant and can lead to cyclic idling, which consumes a lot of CPU. Even adding sleep to the loop is not a particularly good way.
2, in the unique way in iOS, use runloop whether to end as a cyclic judging condition
[Nstimer scheduledtimerwithtimeinterval:[[nsdate distantfuture] timeintervalsincenow] target:self Selector: @selector (ignore:) Userinfo:nil Repeats:yes]; Nsthread *currentthread = [Nsthread CurrentThread]; Nsrunloop *currentrunloop = [Nsrunloop currentrunloop]; BOOL iscancelled = [CurrentThread iscancelled]; NSLog (@ "Hello 1"); while (!iscancelled && [Currentrunloop runmode:nsdefaultrunloopmode beforedate:[nsdate distantfuture]) { NSLog (@ "Hello 2"); iscancelled = [CurrentThread iscancelled]; } NSLog (@ "Hello 3");
Running the above code in the created thread body will output:
2017-03-22 19:28:50.693824 nsthreadtest[3459:785928] Hello 1
At this point the thread is stuck in the while, but is dormant, and when there is an event source in the Runloop, the thread wakes up and executes the method that handles the corresponding event.
It looks pretty magical! When the thread ends, it outputs Hello 3, at which point the CPU is occupied as follows
In addition to the above implementations, there is a more elegant implementation:
/*//Consumes 0% CPU BOOL shouldkeeprunning = YES; Global Nsrunloop *runloop = [Nsrunloop currentrunloop]; [Runloop Addport:[nsmachport Port] Formode:nsdefaultrunloopmode]; Adding some input source, that's required for Runloop to runing while (shouldkeeprunning && [Runloop Runmo De:nsdefaultrunloopmode beforedate:[nsdate Distantfuture]]); Starting infinite loop which can be stopped by changing the shouldkeeprunning ' s value * /*//0% CPU @autoreleasepool { Nsrunloop *runloop = [Nsrunloop currentrunloop]; [Runloop Addport:[nsmachport Port] formode:nsrunloopcommonmodes]; [Runloop run]; } */
3. Summary
Nsthread in iOS is an encapsulation of pthread in UNIX and adds the concept of runloop, which optimizes overall performance in such event-driven threads and facilitates the scheduling of threads.
4. Source code
Https://github.com/liqiushui/NSThreadKeepAlive.git
How IOS keeps threads running