Общая память и атомарные операции
Изучите применение SharedArrayBuffer и атомарных операций для высокопроизводительного параллельного доступа к данным между WASM и JS
«Общая память и атомарные операции» — бесплатный урок WebAssembly (WASM) for High Performance Apps на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения WebAssembly (WASM) for High Performance Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Concurrency & Shared Memory
When building high-performance applications, especially with WebAssembly, you often need to perform tasks concurrently. This means running parts of your code in parallel, perhaps across different threads.
For these concurrent tasks to work together efficiently, they often need to access and modify the same data. This is where shared memory comes in.
Why Not Just ArrayBuffer?
You might already know about ArrayBuffer for handling raw binary data in JavaScript. However, a standard ArrayBuffer cannot be directly shared between different execution contexts (like the main thread and a Web Worker, or between JavaScript and a WebAssembly thread).
Each context would get its own copy of the data, which is inefficient and complicated to synchronize for frequent updates.
Introducing SharedArrayBuffer
The solution for true concurrent data access is SharedArrayBuffer. It's a special type of ArrayBuffer that allows the same memory block to be accessed by multiple threads simultaneously.
This means your JavaScript main thread, Web Workers, and WebAssembly modules can all read from and write to the *exact same* underlying data, enabling efficient communication and complex parallel computations.
Security Headers for Sharing
Due to security vulnerabilities (like Spectre), using SharedArrayBuffer requires specific HTTP response headers to be set by the server:
Cross-Origin-Opener-Policy: same-originCross-Origin-Embedder-Policy: require-corp
These headers ensure that the document is in an isolated, cross-origin isolated browsing context, which is necessary for SharedArrayBuffer to function securely.
Creating SharedArrayBuffer in JS
Creating a SharedArrayBuffer is similar to creating a regular ArrayBuffer. You specify the size in bytes. Then, you can create a typed array view (like Int32Array) to easily interact with the memory.
const sharedBuffer = new SharedArrayBuffer(1024); // 1KB
const sharedArray = new Int32Array(sharedBuffer);
console.log("Shared buffer created!");
console.log("Size:", sharedArray.length * Int32Array.BYTES_PER_ELEMENT, "bytes");WASM's View of Shared Memory
When a SharedArrayBuffer is passed to a WebAssembly module (e.g., via WebAssembly.Memory), WASM can map this memory into its own linear memory space. This allows WASM code to directly read and write to the shared data.
This direct access is key for performance, as it avoids costly data copying between the host environment (JavaScript) and the WASM module.
Race Conditions & Data Safety
While sharing memory is powerful, it introduces a challenge: race conditions. If multiple threads try to read and write to the same memory location at the same time, the final result can be unpredictable or incorrect.
Imagine two threads trying to increment a counter simultaneously. Without proper synchronization, one update might overwrite another, leading to a wrong count.
Introducing Atomics for Safety
To prevent race conditions, JavaScript provides the Atomics object. Atomics offer a set of operations that are guaranteed to be atomic, meaning they are indivisible.
An atomic operation either completes entirely or doesn't happen at all, ensuring that no other thread can interrupt it. This guarantees data integrity in shared memory.
Atomic Reads and Writes
The most basic atomic operations are `Atomics.load()` and `Atomics.store()`. These methods ensure that reading and writing values to a shared memory location happens as a single, uninterruptible step.
const sharedBuffer = new SharedArrayBuffer(4); // 4 bytes
const int32View = new Int32Array(sharedBuffer);
// Safely store a value at index 0
Atomics.store(int32View, 0, 100);
console.log("Stored 100 atomically.");
// Safely load a value from index 0
const value = Atomics.load(int32View, 0);
console.log("Loaded value:", value);Atomic Arithmetic Operations
Beyond simple reads/writes, Atomics provide arithmetic operations like Atomics.add(), Atomics.sub(), Atomics.and(), etc. These perform an operation and update the value atomically.
Atomics.add(typedArray, index, value) adds value to the element at index and returns the old value at that index, all in one safe step.
const sharedBuffer = new SharedArrayBuffer(4);
const int32View = new Int32Array(sharedBuffer);
Atomics.store(int32View, 0, 5); // Initial value
console.log("Initial value:", Atomics.load(int32View, 0));
// Atomically add 3 to the value at index 0
const oldValue = Atomics.add(int32View, 0, 3);
console.log("Old value before add:", oldValue);
console.log("New value after add:", Atomics.load(int32View, 0));Shared Memory Check
Consider the following JavaScript code snippet. Assume sharedBuffer is a properly configured SharedArrayBuffer and int32View is an Int32Array view of it.
const int32View = new Int32Array(sharedBuffer);
Atomics.store(int32View, 0, 5);
const result = Atomics.add(int32View, 0, 2);
const finalValue = Atomics.load(int32View, 0);Recap: Shared Memory & Atomics
We've explored how SharedArrayBuffer enables efficient concurrent data access between JavaScript and WebAssembly by allowing multiple threads to access the same memory block.
To prevent data corruption from race conditions, we learned about Atomics, which provide safe, indivisible operations for reading, writing, and modifying data in shared memory.
These tools are crucial for building high-performance, multithreaded WebAssembly applications.
Часто задаваемые вопросы
Урок «Общая память и атомарные операции» бесплатный?
Да — полный текст урока «Общая память и атомарные операции» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс WebAssembly (WASM) for High Performance Apps, подпишись на CoddyKit PRO. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.
Чему я научусь в уроке «Общая память и атомарные операции»?
Изучите применение SharedArrayBuffer и атомарных операций для высокопроизводительного параллельного доступа к данным между WASM и JS Ты практикуешь WebAssembly (WASM) for High Performance Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать WebAssembly (WASM) for High Performance Apps?
Предыдущий опыт не требуется. WebAssembly (WASM) for High Performance Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Общая память и атомарные операции»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке WebAssembly (WASM) for High Performance Apps?
Да. Каждый урок WebAssembly (WASM) for High Performance Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Передача сложных структур данных
- Модель памяти WASM и управление памятью
- Общая память и атомарные операции
- Увеличение и управление линейной памятью