Distributed Objects, Threads, & graceful thread exits
Distributed Objects, Threads, & graceful thread exits
- Subject: Distributed Objects, Threads, & graceful thread exits
- From: Phill Kelley <email@hidden>
- Date: Mon, 24 Mar 2003 16:31:30 +1100
I'm trying to understand how to manage threads in the context of
Distributed Objects. I've been using the "ThreadExample" from chapter 24 of
Anguish, Buck & Yacktman as my starting point.
In the example code, the threads are created when the app launches and hang
around until the app dies.
What I'm trying to do is to extend the example so that I can tear down and
re-spawn the threads on command.
There have been a number of hints in cocoa-dev emails which have led me to
do the following:
1. Extend the ServerObject class:
a. Add an instance variable:
NSConnection * itsConnection;
b. Extend the initForParent:withTag declaration as follows:
- (id) initForParent:(id <ServerObjectController>)theParent
withConnection:(NSConnection*)theConnection
withTag:(int)theTag
c. Within the body of the revised initForParent method:
itsConnection = theConnection;
[itsConnection retain];
d. Implement dealloc, and include [itsConnection release];
e. Extend _connectWithPorts so that it passes the NSConnection
object it creates to the initForParent call.
2. Extend the ApplicationDelegate object so that the NSConnection
objects returned by the two calls to startServerThreadWithTag
are saved in instance variables:
NSConnection * serverConnection;
NSConnection * messageServerConnection;
3. Add a method to the ServerMethods protocol, implemented as:
- (void)terminate
{
[itsConnection removeRunLoop:[NSRunLoop currentRunLoop]];
}
With all of that preamble in place, if I want to terminate an idle thread
from the main thread, I do the following:
[server terminate];
[[serverConnection receivePort] invalidate];
Given the generally elegant ways in which Cocoa does things, having to go
to all this trouble to tear down a thread seems overly complicated.
Hints found in previous emails on this list have suggested that the only
thing that I *should* need to do to terminate a thread gracefully is one of
the following:
a. [[theInterthreadConnectionInSpawnedThread sendPort] invalidate];
b. [[theInterthreadConnectionInMainThread receivePort] invalidate];
I have found that "a" results in "connection went invalid while waiting for
a reply" console-log messages.
Although "b" seems to tear down the DO, it doesn't appear to cause the
runloop to exit and none of the thread-related objects is released.
While my two-step solution seems to work reliably, I find myself wondering
if it is the most appropriate way in which to cause a DO-based thread to
exit, or if I am missing something vital?
Regards & thanks, Phill
_______________________________________________
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.