0Pricing
WebAssembly (WASM) for High Performance Apps · 강의

공유 메모리 및 원자적 연산

WASM과 JS 사이에서 고성능 동시 데이터 액세스를 구현하기 위해 SharedArrayBuffer와 원자적 연산을 활용하는 방법을 살펴봅니다.

공유 메모리 및 원자적 연산은(는) CoddyKit의 무료 WebAssembly (WASM) for High Performance Apps 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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-origin
  • Cross-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 AI 튜터), CoddyKit PRO로 업그레이드하면 WebAssembly (WASM) for High Performance Apps 강의 전체를 잠금 해제할 수 있습니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“공유 메모리 및 원자적 연산”에서 뭘 배우나요?

WASM과 JS 사이에서 고성능 동시 데이터 액세스를 구현하기 위해 SharedArrayBuffer와 원자적 연산을 활용하는 방법을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 WebAssembly (WASM) for High Performance Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebAssembly (WASM) for High Performance Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebAssembly (WASM) for High Performance Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“공유 메모리 및 원자적 연산” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebAssembly (WASM) for High Performance Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebAssembly (WASM) for High Performance Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 복잡한 데이터 구조 전달
  2. WASM 메모리 모델 및 관리
  3. 공유 메모리 및 원자적 연산
  4. 선형 메모리 확장 및 관리
← WebAssembly (WASM) for High Performance Apps(으)로 돌아가기