Re: threads in Xcode
Re: threads in Xcode
- Subject: Re: threads in Xcode
- From: Mai Bui <email@hidden>
- Date: Mon, 19 Jul 2004 16:36:45 -0700
Thanks for your reply.
After modify my code:
- (IBAction)runButton:(id)sender
{
[sender setEnabled:NO]; // disable the run button
[NSThread detachNewThreadSelector: @selector(runLoop:) toTarget:self
withObject:nil];
NSLog(@"Press run button...\n");
}
- (void) runLoop:(id)object
{
int i;
NSAutoreleasePool *runPtr = [[NSAutoreleasePool alloc] init];
NSString *str = @"print out the string\n";
for (i=0; i<1500; i++)
{
[statusText insertText:str]; // use insertText since statusText is
NSTextView class
NSLog(@"Running... %d\n",i);
}
NSLog(@"End of runloop!%d\n",i);
[runPtr release];
}
- (IBAction)stopButton:(id)sender
{
NSAutoreleasePool *stopPtr = [[NSAutoreleasePool alloc] init];
[NSThread detachNewThreadSelector: @selector(runLoop:) toTarget:self
withObject:nil];
[self performSelectorOnMainThread:@selector(hasStopped)
withObject:NULL waitUntilDone:false];
NSLog(@"Press stop button\n");
[stopPtr release];
}
Now, it has a strange behavior. Sometime, it run through a loop,
sometime it stop in the middle way with a error message:
"2004-07-19 15:36:08.788 StopApp[1053] An uncaught exception was raised
2004-07-19 15:36:08.788 StopApp[1053] *** -[NSCFArray objectAtIndex:]:
index (0) beyond bounds (0)
2004-07-19 15:36:08.788 StopApp[1053] *** Uncaught exception:
<NSRangeException> *** -[NSCFArray objectAtIndex:]: index (0) beyond
bounds (0)
StopApp has exited due to signal 5 (SIGTRAP)."
Another thing I understand that one thread can not stop the other
thread (eg. stopButton() stop runButton() thread) but stopButton() can
set the flag for runButton() check whether it should keep going run or
not. In this point, should I use global var for this flag?
For example:
...
BOOL stopState;
(in the initial:
...
stopState = false;
...)
...
(and the runLoop())
- (void) runLoop:(id)object
{
int i;
NSAutoreleasePool *runPtr = [[NSAutoreleasePool alloc] init];
NSString *str = @"print out the string\n";
for (i=0; i<1500; i++)
{
[statusText insertText:str]; // use insertText since statusText is
NSTextView class
NSLog(@"Running... %d\n",i);
if (stopState)
break;
}
NSLog(@"End of runloop!%d\n",i);
[runPtr release];
}
(and the stopButton() )
- (IBAction)stopButton:(id)sender
{.....
stopState = true;
.....
}
but while the runLoop() executed, stopButton() can not executed until
runLoop() done, so the "stopState" is never assigned when the user
press "STOP" button in order to stop runLoop().
I have no clue!
Thanks again your knowledge.
Mai.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.