kaykun
kaykun

Reputation: 2267

Is open thread safe?

Is it okay if two threads call open() at the same time? How would one find the answer to this question?

Assume that the calls are operating on different files, and their flags can be O_RDONLY, O_WRONLY, or both.

Upvotes: 3

Views: 4858

Answers (4)

Guy Sirton
Guy Sirton

Reputation: 8421

It depends on the operating system and C run time library. If it is POSIX.1-2001 or POSIX.1-2008 compliant then it must be thread safe as per here: http://www.kernel.org/doc/man-pages/online/pages/man7/pthreads.7.html

As others noted just because system calls may be thread safe doesn't mean you can do anything and expect the calls to magically figure things out for you. If you write and read the same file from different threads without proper synchronization the results will be indeterminate. The thread safety in this context just means the reads and writes will execute. Another way of thinking about it is that you get the same guarantees as if the calls were made in different processes. Everyone has an expectation of system calls such as open() being "process safe" because otherwise the OS would be useless.

Upvotes: 5

anonymous
anonymous

Reputation: 11

Whether they're to the same file or different is actually a red herring. If you're running on a Unix-like OS, when open() is a direct system call, the answer is absolutely yes. Different threads can open files (or even the same file) at the same time just as different processes can.

If you're running on a system that emulates open() in user-space, the likely source of non-thread-safety is the file descriptor table that maps the file handle returned by the OS to the small integer file descriptor that a Unix-like open() call returns. As another poster noted, POSIX requires that open() be thread-safe, and as open() is generally implemented to provide POSIX compatibility, it'll be safe.

It is conceivable that a very old and creaky C library might provide a non-thread-safe open(), but it's pretty unlikely that you'll encounter it. Especially if you are using POSIX threading.

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76918

Since you note they are different files, then there isn't a problem.

It's no different that two different processes opening two different files.

Edit: It would be fair to mention, as Guy notes below in the comments, that this was not always the case. It is dependent on whether the libc you are using is threadsafe. Modern incarnations are in regard to the open() call.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 191058

It depends. Are you opening for reading? Then it is safe. If you are opening for writing, then you should synchronize the threads.

Upvotes: -1

Related Questions