Re: FileHandle in Threads
Re: FileHandle in Threads
- Subject: Re: FileHandle in Threads
- From: "Gerriet M. Denkmann" <email@hidden>
- Date: Fri, 6 Oct 2006 09:04:31 +0200
On 6 Oct 2006, at 06:27, email@hidden wrote:
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.
Closing the file descriptor happens when I unplug the USB-device.
The main thread notices this, releases its file handle and tells the
reader thread to do likewise.
But I'll change the main thread not to closeOnDealloc.
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.)
The main thread needs the file handle, because it will go on writing
to it ([NSFileHandle writeData:]) occasionnally.
Kind regards,
Gerriet.
_______________________________________________
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