К теме
По желанию
fork/COW против потоков
Для 4 задач выбрать process или thread; отметить адресное пространство и COW после fork.
- Версия
- v2
- Минут
- ~20
- Проверка
- Самопроверка в ноутбуке
Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.
Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.
Содержимое ноутбука
Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.
CA · fork/COW против потоков / fork/COW vs threads
Activity version: 2 · Seed: 7 · Данные: four toy tasks plus a page-array model of COW vs shared-thread memory.
Choose process or thread for each task; after fork+write, COW diverges pages while threads share the write.
Ожидаемые числа
| Task | Choice | Shared AS? |
|---|---|---|
run another program (exec) |
process | no |
| parallel sum over a shared array | thread | yes |
| isolate an untrusted plugin | process | no |
| many short workers, shared heap | thread | yes |
| after fork, parent writes page 0 | child stays ; parent | COW |
| two threads write page 0 | both see | shared |
Самопроверка в ноутбуке
Активность не входит в процент освоения.
import numpy as np
rng = np.random.default_rng(7)
tasks = [
("exec_other_program", "process", False),
("parallel_sum_shared_array", "thread", True),
("isolate_untrusted_plugin", "process", False),
("many_short_workers_shared_heap", "thread", True),
]
assert [kind for _, kind, _ in tasks] == ["process", "thread", "process", "thread"]
assert [shared for _, _, shared in tasks] == [False, True, False, True]
# Shared physical pages until a write; then the writer gets a private copy (COW).
phys = {
0: np.array([10, 11], dtype=int),
1: np.array([20, 21], dtype=int),
2: np.array([30, 31], dtype=int),
3: np.array([40, 41], dtype=int),
}
next_frame = 4
parent_map = {i: i for i in range(4)}
child_map = {i: i for i in range(4)}
cow = {i: True for i in range(4)}
def write(maps, pid, vpn, new_row):
global next_frame
frame = maps[pid][vpn]
if cow[frame]:
phys[next_frame] = phys[frame].copy()
maps[pid][vpn] = next_frame
cow[frame] = False
cow[next_frame] = False
next_frame += 1
frame = maps[pid][vpn]
phys[frame] = np.array(new_row, dtype=int)
maps = {"parent": parent_map, "child": child_map}
write(maps, "parent", 0, [99, 99])
parent_page = phys[parent_map[0]]
child_page = phys[child_map[0]]
print("parent", parent_page, "child", child_page)
assert list(parent_page) == [99, 99]
assert list(child_page) == [10, 11]
assert parent_map[0] != child_map[0]
# Threads share one address space: one write is visible to both views.
shared = np.array([[10, 11], [20, 21]], dtype=int)
t1 = t2 = shared
t1[0] = np.array([99, 99])
assert list(t2[0]) == [99, 99]
assert int(rng.integers(0, 100)) == 94
print("OK: fork/COW vs threads")
Самопроверка в ноутбуке
- 4 задачи: process / thread / process / thread
- после fork+write ребёнок сохраняет
- потоки оба видят