Re: FileHandle in Threads
Re: FileHandle in Threads
- Subject: Re: FileHandle in Threads
- From: AgentM <email@hidden>
- Date: Thu, 5 Oct 2006 15:03:19 -0400
On Oct 5, 2006, at 14:48 , Gerriet M. Denkmann wrote:
I have an app with 2 thread: main and reader.
Main opens an NSFileHandle and writes to the file (actually a
serial port) then passes the NSFileHandle to the reader thread for
reading.
This fails because the reader thread does not really get a file
handle, but rather an NSDistantObject acting as proxy for the file
handle. [fileHandle availableData] creates an exception complaining
about proxies.
So far so good.
Now I pass the file descriptor to the reader, and it does
NSFileHandle *f = [[NSFileHandle alloc] initWithFileDescriptor: fd
closeOnDealloc: YES];
(the main thread did exactly the same).
Is this a problem: having two file handles pointing to the same
file descriptor?
(It seems to be working - but is this just luck or solidly based on
good design?)
And: should both threads use closeOnDealloc: YES, or just one?
(Again: having both threads using YES does seem to work).
You're not breaking any rules (you say it works) but your approach is
not necessarily the best.
1) Closing the file descriptor from two separate threads either a)
silently swallows the error or b) the app is quitting so the
deallocations never happen.
2) You should use the notion of a resource owner. In this case, you
probably want to hand off the ownership of the NSFileHandle object to
the secondary thread. To make your code kosher, you should create the
object, pass it off to the thread and release the object from your
main thread. Meanwhile, the reader thread has accepted responsibility
for the object and retained it. The main thread should then never
need the object again (or does it? Then you need some syncing.)
Good luck.
-M
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden