views:

15

answers:

1

I would like to implement a multi-threaded, non-blocking file open. Ideally, the desired solution would be to make a call to open() & have it return immediately, and do something like register a callback to be called (or handle a signal, or conditional variable) when the open() operation is actually complete. To that end, I wrote a little test driver that creates multiple simultaneous threads and tries to open the same file. I would have hoped the return from openat() to be an invalid file descriptor, with an errno == EAGAIN, but the open call seems to always block until the open completes successfully.

Is there an implementation of this approach for a non-blocking open()?

Thanks in advance.

Reference Thread Code:

void* OpenHandler(void* args)
{

// Declarations removed

   Dir = "/SomeDir";

   if ((DirFd = open(Dir, O_RDONLY )) < 0) {
      printf("********Error opening Directory*******\n");
      return NULL;
   }


   do {

      FileFd = openat(DirFd, &FileName[DirLen], O_RDONLY | O_NONBLOCK);

      /* If open failed */
      if (FileFd == -1) {
         if (errno == EAGAIN)
            printf("Open would block\n");
         else {
            printf("Open failed\n");
            pthread_exit(NULL);
         }
      }
      else
         Opened = 1;

   } while (!Opened);

   pthread_exit(NULL);
}
+1  A: 

open() and openat() always fully resolve the open request in one shot (normally, this doesn't need to sleep, but it can if directory entries need to be brought in from disk or over the network).

To do what you want, you'll have to build a thread pool of file-opening threads, that perform the open() on behalf of the thread you want to continue working and notify it when the open is complete. Unless you're opening a lot of files on very slow network filesystems, I doubt the juice will be worth the squeeze.

caf