views:

71

answers:

2

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];
}
A: 

Basically, you want to keep track of the number of threads you have running, and also assign each thread a unique ID. Assuming that startThread is an event handler for your button, you might have something like:

static int threadIndex = 0;
static int threadsRunning = 0;

-(void)startThread {
    NSNumber* threadId = [NSNumber numberWithInt:threadIndex++];
    threadsRunning++;
    [self performSelectorInBackground:@selector(myThread) withObject:threadId];
}

Then when you stop a thread, you just decrement threadsRunning.

Looking at your code, though, I'm confused by your stopTread method, since it seems to be doing the exact same thing as the myThread method, i.e., not stopping the thread at all.

Shaggy Frog
would I use [NSThread exit]? Thanks.
Crystal
No need with your current setup. The threads you're starting are just going to call `updateDisplay` once and then exit.
Shaggy Frog
A: 

You're performing stuff in the background, which is distinct from explicitly creating threads (e.g. it might reuse threads in a thread pool).

If you want really inefficient threading code, you could use something like this:

NSThread * thread = [[[NSThread alloc] initWithTarget:self selector:@selector(myThread) object:nil] autorelease];
[thread start];
while ([thread isExecuting])
{
  NSLog(@"Still running");
  [NSThread sleepForTimeInterval:0.1];
}

EDIT: If you're actually going to do iPhone development, I recommend looking at NSOperation/NSInvocationOperation/NSBlockOperation instead. Thread management is a real pain to get right.

tc.