Is there a reason to open a file with shared access?

I always opened my files in two ways: read access and read sharing, read / write access and sharing.

It seems to me that the permission of shared-write could always lead to unexpected things that happen to the file while it is being read. Are there any good reasons to open a file in shared recording mode?

+4
source share
3 answers

If a file is used by many processes, it is sometimes impractical to lock the entire file (for performance reasons).

In this case, you can lock the file area while writing.

On Windows, you can use the LockFile () function.
On Linux / Unix, you can use fcntl () or flock ()

+2
source

I will be afraid of conjecture ... one thing he can use is for parallel computing. Suppose you have two threads that perform very parallel computations, and you want the data to be written to one file. You can also pre-determine the size needed to store the output of each stream (say, 50 MB).

So, select a 100 MB file, start the stream starting recording at offset 0, and start stream # 2 with 50 MB. When the streams are completed, you will have one single file (otherwise, using separate files, you need to add the result from stream # 2 to stream # 1).

ASCII Art Attempt

============================== | 50MB | 50MB | [100 MB Total FileSize] | | | ============================== ^ ^ | | Thread 1 Thread 2 

All that said, I never did that. It may not even work! You can simply share the file handle / stream between threads using some other synchronization mechanism, but then you will also have to reset the offset in each stream. Perhaps this or that is more effective.

On the one hand, there can be many disks if both streams are always written the same. Conversely, record synchronization can adversely affect the benefits of concurrency if there is a lot of controversy in record locking. And, as they often say, a profile and a test!

In any case, Iโ€™m also interested in the โ€œreal lifeโ€ scenario, which uses record sharing, and will monitor for additional answers!

+1
source

Sockets are lower than File I / O.

Suppose that the server is listening on some local port 1999 and sends incoming messages to all subscribers on service port 3128.

The server can read data from several local clients and transfer them to several remote clients. If the server was an authentication daemon, several local applications may try to authenticate using the same server (service). Remote clients may be informed that user-x is now authenticated because he / she has successfully logged into one of the public application sharing servers.

I donโ€™t know what I'm talking about. I dare to speculate.

+1
source

Source: https://habr.com/ru/post/1285835/


All Articles