开发者

Multithreaded file reading, does seek & read need critical section?

I have a file that will be read from multiple threads, do I need to put each seek and read into a critical section?

stream.Seek(seekStart, 开发者_如何学编程SeekOrigin.Begin);
stream.Read();
stream.Seek(seekNext, SeekOrigin.Current);
stream.Read();

or

lock(fileLock)
{
    stream.Seek(seekStart, SeekOrigin.Begin);
    stream.Read();
    stream.Seek(seekNext, SeekOrigin.Current);
    stream.Read();
}

Obviously what I'm trying to avoid is the following situation:

.
.
 Thread A: Seek
 <- Preempted ->
 Thread B: Seek
 Thread B: Read
 <- Preempted ->
 Thread A: Read  (Will this be reading from the wrong location?)
.
.


Because your streams will be separate objects in separate threads, you should be OK without making it critical. Each stream should hold its own seek location, and so should not interfere with the others.

This assumes that you are declaring all of your variables within the class object, and not static.


Whenever you're modifying an object which is shared across threads, you need a critical section.

If the stream variable is being shared (referring to the same object), then yes.

If each thread has its own stream variable (not referring to the same object), then no.


if it is the same stream you would need for each seek and read to be in a critical section...

Alternatively you can use MemoryMappedFile (ne in .NET 4)... this allows multiple threads to access it without crisitcal section because it maps the file into RAM and then you can random access its content...


MSDN say for FileStream"

When a FileStream object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the FileStream object and the cached data in the buffer could be compromised. The FileStream object routinely performs checks on methods that access the cached buffer to assure that the operating system's handle position is the same as the cached position used by the FileStream object.

If an unexpected change in the handle position is detected in a call to the Read method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.

So at least, you can have performance issues. For performance, the best solution is to use Asynchronuous I/O (BeginRead, EndRead)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜