[Spread-users] Question about thread-safety

John Schultz jschultz at commedia.cnds.jhu.edu
Mon Jun 16 18:16:13 EDT 2003


On Mon, 16 Jun 2003, George Schlossnagle wrote:

> On Monday, June 16, 2003, at 05:38  PM, John Schultz wrote:
>
> >>> NOTE: if anyone knows how to instruct Unix/Linux systems not to
> >>> reuse file descriptor IDs in a process, could you please email me or
> >>> the list a good reference (with page #)? Thanks!
> >
> >> It is part of the guaranteed semantics of open() that it returns the
> >> lowest available file descriptor, so there's definitely no way to do
> >> this unless you simply keep it open.
> >
> > Doesn't this cause a general race condition in multi-threaded
> > Unix/Linux applications that open and close file descriptors in
> > multiple threads?
> >
> > The race condition: a thread is about to operate on file descriptor x,
> > but just before it does another thread(s) close x and create a new
> > file descriptor which is assigned the same value as x.
> >
> > To avoid this race condition wouldn't all calls that create and/or
> > close file descriptors have to be done in a single thread that ensures
> > no other threads are operating on any file descriptors it is about to
> > close? If so, that seems like a BAD thing to me.
>
> Why can't you use a mutex to protect these sorts of accesses?
>

On Mon, 16 Jun 2003 17:53:12 -0400, Jonathan Stanton wrote:

> I agree with multithreaded programs this behaviour requires you to
> synchronize fd creation/destruction and not treat fd's as globally
> unique 'eternal' ids, but rather globally unique 'at one point in time'
> ids. But is this really such a big deal?


Now that you guys mentioned it, I realized that you can.  I was worried
previously about holding onto a lock while in a system call (read(),
etc.), but if the lock is solely dedicated to protecting the fd, then we
can make those calls atomic.

Something like this then:

typedef struct {
  pthread_mutex_t lock;
  int fd_err;
  int fd;

} fd_protector;

Then you need to ensure that all threads stop using this fd_protector
before closing the file descriptor and garbage collect the fd_protector --
of course doing all this basically is the BAD thing that I mentioned
above.

Sorry for spamming the list with this issue. :)

---
John Schultz
Co-Founder, Lead Engineer
D-Fusion, Inc. (http://www.d-fusion.net)
Phn: 443 838 2200





More information about the Spread-users mailing list