开发者

Keeping track of multiple threads on iphone

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 {
    co开发者_Python百科unt = 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 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜