Motivation

What is atomic operation?

我們將原本要多個 system call 才能完成的操作包成一個保證會連續執行,不會有其他 process 在你執行 automic operation 時更改你要存區的東西

Why do we need atomic operation?

上圖藍綠兩色開啟同一個檔案並且他們都想要在那個檔案的結尾上 write

因為這個過程不是 atmoic 的,結果藍色 process 最後並沒有在檔案末尾 write,而是覆蓋了綠色 process 的 write

When should operations be atomic?

We make operations atomic if the result of the operation depends on “shared resources”

pread/pwrite

#include <unistd.h>
ssize_t pread(int filedes, void *buf, size_t nbytes, off_t offset);
ssize_t pwrite(int filedes, const void *buf, size_t nbytes, off_t offset);
  • pread is lseek then read but atomic
  • pwrite is lseek then write but atomic