July 2nd, 2021

Is it okay to call Map­View­Of­File on the same mapping handle simultaneously from different threads?

A customer found that a bottleneck in their program was traced to the way they use the Map­View­Of­File function. Specifically, they use an application-level lock to ensure that two threads do not call use the Map­View­Of­File on the same mapping handle at the same time. The customer wanted to know whether this lock was required. Is it okay to call Map­View­Of­File on the same mapping handle simultaneously from different threads?

Certainly the kernel needs to provide a basic level of protection against simultaneous use, in that the kernel can’t crash or corrupt memory. That would be a serious security issue. The real question is whether making two simultaneous calls has the same effect as making the calls sequentially: Assuming sufficient resources are available, do both both calls succeed and create distinct views? Or can the kernel fail one of the calls with ERROR_BUSY or something like that?

The kernel permits simultaneous calls on the same handle, and they operate independently. You don’t need to serialize your calls to Map­View­Of­File.

The next question is whether removing the application lock will actually help anything. After all, if the kernel is doing its own synchronization, then all you did was move the bottleneck from the application lock to the kernel lock.

Yes, it will help. The kernel needs to take a lock to synchronize changes to the process address space, but the scope of that lock is narrower than the entire mapping operation and therefore will have reduced contention compared to what the application is imposing with its own lock.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

3 comments

Discussion is closed. Login to edit/delete existing comments.

  • Alex Martin

    Wow! An application that does more thread-safety than is actually needed! It’s almost surprising to see a story about an overly-cautious customer on this blog.

    • Erik Fjeldstrom

      People who follow the rules don’t make for very interesting stories most of the time.

      • Alex Martin

        Which itself makes it interesting that this one did.