I’m trying to do something basic to understand threads with a counter that just increments when a button is pressed, and every time the button is pressed, a new thread incrementing the same counter starts. Then I have a stop button to stop a thread that is running. How can I tell how many threads, or which thread is running? Here is my basic template I am working on. Thanks.
-(int)count {
return count;
}
-(void)setCount:(int) value {
count = value;
}
-(void)updateDisplay {
countLabel = [NSString stringWithFormat:@"%i", count];
count++;
}
-(void)myThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:@selector(updateDisplay)
withObject:nil
waitUntilDone:NO];
[pool release];
}
-(void)startThread {
[self performSelectorInBackground:@selector(myThread) withObject:nil];
}
-(void)myThreadStop {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:@selector(updateDisplay)
withObject:nil
waitUntilDone:NO];
[pool release];
}
-(void)stopThread {
[self performSelectorInBackground@selector(myThreadStop) withObject:nil];
}
Basically, you want to keep track of the number of threads you have running, and also assign each thread a unique ID. Assuming that
startThreadis an event handler for your button, you might have something like:Then when you stop a thread, you just decrement
threadsRunning.Looking at your code, though, I’m confused by your
stopTreadmethod, since it seems to be doing the exact same thing as themyThreadmethod, i.e., not stopping the thread at all.