Copy-on-write (COW), also known as implicit sharing or shadowing, is a resource-management technique used in computer programming to efficiently implement a "duplicate" or "copy" operation on modifiable resources [1]. It is commonly used in various contexts, such as memory management, operating systems, software libraries, and storage systems.
In virtual memory management, copy-on-write finds its main use in operating systems that share the physical memory of computers running multiple processes, particularly in the implementation of the fork() system call [1]. When a new process is created, it initially shares the same memory pages as the parent process. This avoids the need to immediately copy all of the parent process's memory, which would waste processor time and memory. Instead, the operating system marks certain pages of memory as read-only and keeps a count of the number of references to the page. When data is written to these pages, the operating system intercepts the write attempt and allocates a new physical page, initialized with the copy-on-write data. The page table is then updated with the new writable page, and the write operation is performed. This ensures that a change in the memory of one process is not visible in another's [1].
Copy-on-write can also be used to support efficient memory allocation by keeping one page of physical memory filled with zeros. When memory is allocated, all the pages returned refer to the page of zeros and are marked as copy-on-write. Physical memory is only allocated for the process when data is written, allowing processes to reserve more virtual memory than physical memory and use memory sparsely [1].
In software, copy-on-write is used in various contexts. For example, in the C++ standard library, the string class was designed to allow copy-on-write implementations [1]. In the PHP programming language, all types except references are implemented as copy-on-write, allowing them to act as value types without the performance problems of copying on assignment [1]. The Qt framework also uses copy-on-write for many types, allowing them to be safely used by multiple threads without the need for locking mechanisms [1].
In computer storage, copy-on-write may be used as the underlying mechanism for snapshots in logical volume management, file systems like Btrfs and ZFS, and database servers like Microsoft SQL Server [1]. Snapshots created using copy-on-write store only the modified data and are stored close to the original, providing a form of incremental backup [1].
Learn more:
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!