iPhone - Can't kill my thread with loop
I see "killThread" in my log, but the thread doesn't stop. If I set mKillThread to true before calling the loop it will never run. I tried simply bool mKillThread and using a property and self.mKillThread... Below are the only references to mKillThread in the code.
Init:
mKillThread = false;
//mKillThread = true;
[NSThread detachNewThreadSelector:@selector(threadLoop) toTarget:self withObject:nil];
Thread stuff:
// Called on main thread
- (void)killThread {
NSLog(@"killThread");
mKillThread = true;
}
- (void)threadLoop {
while ( !mKillThread ) {
if ( mKillThread ) {
开发者_开发百科NSLog(@"killthread haha!");
return;
}
NSLog(@"looping!");
}
}
EDIT -
Figured it out, I had 2 views in the xib set to MyViewSubclass so I was creating 2 threads. I was only calling killThread on the custom view I had hooked up and not the other. OMG.
Try setting your variable mKillThread to volatile. That will say to the compiler that this variable will be used in more than one thread, and it shouldn't do some optimization which could cause your problem.
volatile bool mKillThread;
Presumably the compiler optimized away the if
clause altogether, because it can infer that inside the while
loop mKillThread
must be false
, therefore if
clause is not necessary.
Note that (Objective-)C(++) compiler is allowed to do this kind of optimizations.
To tell the compiler that a variable can be accessed from another thread and so on, use volatile
.
Or accessing it via the getter also suffices, [self mKillThread]
.
精彩评论