Re: some NSThread questions
Re: some NSThread questions
- Subject: Re: some NSThread questions
- From: Dustin Voss <email@hidden>
- Date: Mon, 31 May 2004 17:42:50 -0700
On 31 May, 2004, at 3:32 PM, Koen van der Drift wrote:
Hi,
I just started learning about using thread, and have some questions.
I want to control the start and end of an NSThread by a start and stop
button. When the user pushes the start button, I want to disable it to
prevent a new NSThread to start. Disabling the button works fine, but
where do I put the call to enable it back when the thread is finished?
-(IBAction)start:(id)sender
{
[sender setEnabled:NO];
// start a new thread
[NSThread detachNewThreadSelector: @selector(run:)
toTarget: self
withObject: nil];
}
Before your thread exits, use a call like [self
performSelectorOnMainThread:@selector(hasStopped)]. Because -hasStopped
runs on the main thread, it will be safe to call -setEnabled:.
Also, when I use the stop button, the thread apparently stops (I get
no more output from the calculation), but the stop button remains
blue, and after a while I get a spinning beachball. It could well be
related to somthing in the calculation, but just to be sure, this is
what I use to stop the thread:
-(IBAction)stop:(id)sender
{
[NSThread exit];
// myPrintf("Calculation was interrupted by the user");
}
This is not the correct way to stop a thread. Threads can only safely
stop themselves. The thread will have to periodically check a flag to
see if it should keep running. When you want the thread to stop, set
the flag. The thread should stop itself (by exiting -run:) the next
time it checks the flag.
Finally, I read something about the AppKit being thread unsafe. During
the calculation in the second thread many results are displayed in an
NSTextView, using calls like:
[theResultsTextView replaceCharactersInRange:
NSMakeRange([[theResultsTextView string] length], 0)
withString:s];
Do I need to sandwich this code with a lock?
A lock won't do the trick. Use -performSelectorOnMainThread:.
_______________________________________________
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.