For faster navigation, this Iframe is preloading the Wikiwand page for 寫入時複製.

寫入時複製

寫入時複製(英語:Copy-on-write,简称COW)是一种计算机程式設計領域的优化策略。其核心思想是,如果有多個呼叫者(callers)同時请求相同資源(如内存或磁盘上的数据存储),他們會共同取得相同的指標指向相同的資源,直到某個呼叫者试图修改資源的内容時,系統才會真正複製一份专用副本(private copy)給該呼叫者,而其他呼叫者所见到的最初的资源仍然保持不变。這過程對其他的呼叫者都是透明的。此作法主要的優點是如果呼叫者沒有修改該資源,就不會有副本(private copy)被建立,因此多个呼叫者只是读取操作时可以共享同一份资源。

应用

虚拟内存管理中的写时复制

一般把这种被共享访问的页面标记为只读。当一个task试图向内存中写入数据时,内存管理单元(MMU)抛出一个异常,内核处理该异常时为该task分配一份物理内存并复制数据到此内存,重新向MMU发出执行该task的写操作。

数据存储中的写时复制

Linux等的文件管理系统使用了写时复制策略。

数据库服务器也一般采用了写时复制策略,为用户提供一份snapshot。

软件应用中的写时复制

C++标准程序库中的std::string类,在C++98/C++03标准中是允许写时复制策略。但在C++11标准中为了提高并行性取消了这一策略。[1] GCC从版本5开始,std::string不再采用COW策略。

std::string x("Hello");
std::string y = x;  // x 和 y 使用相同的 buffer
y += ", World!";    // y 现在用了不同的 buffer,而 x 用原来的 buffer

PHP中,除了引用类型外,其他类型都是以写时复制的方式实现的。例如,字符串和数组是通过引用传递的。当它们被修改时,如果它们的引用计数不为零,就会复制一份。这使得它们可以像值类型一样使用,而不会有赋值时复制的性能问题。[2]

参考文献

  1. ^ Concurrency Modifications to Basic String. Open Standards. [2015-02-13]. (原始内容存档于2021-02-24). 
  2. ^ Pauli, Julien; Ferrara, Anthony; Popov, Nikita. Memory management. PHP Internals Book. 2013 [2023-11-17]. (原始内容存档于2023-11-10) (英语). 
{{bottomLinkPreText}} {{bottomLinkText}}
寫入時複製
Listen to this article

This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?