views:

142

answers:

1

I have a CFile object, which can be accessed by multiple threads. There is the possibility that one thread is writing data to this file while another thread is reading data from the file. I want to know is there any unsafety under this policy? Can the file pointer change before the write or read process complete? Is the answer is yes, how to avoid the unsafety of multi-thread which can be reading or writing at the same time?

Thank you very much!

A: 

CFile objects are not thread-safe. If you need to access them from multiple threads, you'll need to perform your own synchronization.

From http://msdn.microsoft.com/en-us/library/aa270950.aspx:

Accessing Objects from Multiple Threads

For size and performance reasons, MFC objects are not thread-safe at the object level, only at the class level. This means that you can have two separate threads manipulating two different CString objects, but not two threads manipulating the same CString object. If you absolutely must have multiple threads manipulating the same object, protect such access with appropriate Win32 synchronization mechanisms, such as critical sections. For more information on critical sections and other related objects, see in the Win32 SDK.

The class library uses critical sections internally to protect global data structures, such as those used by the debug memory allocation.

Michael Burr