[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+163 -63
View File
@@ -2,91 +2,191 @@
id: wiki-2026-0508-concurrent-programming
title: Concurrent Programming
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-COPR-001]
aliases: [Concurrency, Multithreading, Async Programming]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [auto-reinforced, concurrent-programming, Parallel-Computing, multi-threading, Scalability, software-engineering]
confidence_score: 0.9
verification_status: applied
tags: [programming, concurrency, parallelism, systems]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: Go, Rust, Python, JavaScript
framework: tokio, asyncio, goroutines
---
# [[Concurrent Programming|Concurrent Programming]]
# Concurrent Programming
## 📌 한 줄 통찰 (The Karpathy Summary)
> "멀티태스킹의 기술: 여러 작업을 동시에 수행하는 것처럼 보이게 하거나 실제로 동시에 실행함으로써, CPU 자원을 놀리지 않고 고성능 대규모 시스템을 지탱하는 현대 소프트웨어의 필수 근육."
## 한 줄
> **"매 concurrency 매 task 의 interleaving — parallelism 의 simultaneous 와 별개"**. Hoare CSP, Hewitt Actor 의 lineage. 2026 매 Rust async, Go goroutines, Java virtual threads (Project Loom GA), Python free-threaded mode 매 mainstream.
## 📖 구조화된 지식 (Synthesized Content)
병행 프로그래밍(Concurrent Programming)은 여러 개의 연산이 겹치는 기간 동안 실행되도록 설계된 프로그래밍 패러다임입니다.
## 매 핵심
1. **핵심 개념**:
* **Concurrency vs Parallelism**: 병행성은 작업들이 '겹치는 시간'에 진행되는 논리적 개념이고, 병렬성은 실제로 '동시에' 수행되는 물리적 개념.
* **Race Condition**: 여러 프로세스가 공유 자원에 동시에 접근할 때 결과가 예측 불가능해지는 치명적 버그.
* **Synchronization**: 데이터 무결성을 위해 임계 구역(Critical Section)을 잠그는(Lock) 등의 조정 기술.
2. **왜 중요한가?**:
* 멀티코어 CPU 시대에 하드웨어 성능을 온전히 끌어내기 위한 유일한 방법이며, 수백만 명의 동시 접속자를 처리하는 서버 아키텍처의 핵심임. (Scalability와 연결)
### 매 Concurrency vs Parallelism
- **Concurrency**: 매 dealing-with-many things at once (composition).
- **Parallelism**: 매 doing-many things at once (execution).
- 매 concurrent 코드 매 single-core 매 still concurrent. 매 parallel 매 multi-core required.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 프로그래밍 정책은 '스레드(Thread)'를 직접 관리하며 고통받는 정책이었으나, 현대 정책은 '코루틴(Coroutine)'이나 '액터 모델(Actor Model)' 같은 고수준 추상화 정책을 통해 안전하고 쉬운 병행성 정책을 지향함(RL Update).
- **정책 변화(RL Update)**: AI 추론 정책에서, 수만 개의 연산을 병렬로 처리하는 GPU 아키텍처 환경에 최적화된 '대규모 병렬 연산 프로그래밍 정책'이 지능화의 물리적 토대가 됨.
### 매 Primitives
- **Threads / processes**: 매 OS-level. Heavyweight.
- **Coroutines / fibers / virtual threads**: 매 user-mode lightweight.
- **Async / await**: 매 cooperative scheduling.
- **Channels**: 매 message passing (Go, Rust mpsc).
- **Mutex / RWLock / Semaphore**: 매 shared-memory sync.
- **Atomic**: 매 lock-free primitive.
## 🔗 지식 연결 (Graph)
- [[Scalability|Scalability]], [[Backend|Backend]], [[Blocking|Blocking]], [[Technical-Architecture|Technical-Architecture]], [[Optimization|Optimization]]
- **Modern Tech/Tools**: Go (Goroutines), Rust (Ownership model), Node.js (Event Loop), CUDA (GPU parallelism).
---
### 매 응용
1. Web server: 매 1 connection-per-virtual-thread (Loom) / async (tokio).
2. Pipeline: 매 channel-based fan-out / fan-in.
3. Actor system: 매 isolation per actor + supervision (Erlang/Elixir, Akka).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Go: goroutine + channel
```go
package main
**언제 쓰면 안 되는가:**
- *(TODO)*
import "fmt"
## 🧪 검증 상태 (Validation)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
results <- j * 2
}
fmt.Println("worker", id, "done")
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= 9; j++ { jobs <- j }
close(jobs)
for r := 1; r <= 9; r++ { <-results }
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Rust: tokio + select!
```rust
use tokio::{select, time::{sleep, Duration}};
**선택 A를 써야 할 때:**
- *(TODO)*
#[tokio::main]
async fn main() {
let task1 = async { sleep(Duration::from_millis(100)).await; "fast" };
let task2 = async { sleep(Duration::from_millis(200)).await; "slow" };
select! {
v = task1 => println!("got {v}"),
v = task2 => println!("got {v}"),
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Java 21+: virtual threads
```java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
}));
} // 10k virtual threads, ~negligible memory
```
**기본값:**
> *(TODO)*
### Python: asyncio TaskGroup (3.11+)
```python
import asyncio
import httpx
## ❌ 안티패턴 (Anti-Patterns)
async def fetch(client, url):
r = await client.get(url)
return r.status_code
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
async def main():
async with httpx.AsyncClient() as client:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(client, u)) for u in URLS]
results = [t.result() for t in tasks]
```
### Rust: structured concurrency (tokio JoinSet)
```rust
use tokio::task::JoinSet;
let mut set = JoinSet::new();
for url in urls { set.spawn(fetch(url)); }
while let Some(res) = set.join_next().await {
println!("{:?}", res?);
}
```
### Lock-free atomic counter
```rust
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
fn bump() -> u64 {
COUNTER.fetch_add(1, Ordering::Relaxed)
}
```
### Actor pattern (Elixir)
```elixir
defmodule Counter do
use GenServer
def start_link(_), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__)
def init(s), do: {:ok, s}
def handle_call(:inc, _, s), do: {:reply, s+1, s+1}
end
```
### Backpressure with bounded channel
```go
sem := make(chan struct{}, 10) // max 10 concurrent
for _, url := range urls {
sem <- struct{}{}
go func(u string) { defer func(){ <-sem }(); fetch(u) }(url)
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| I/O-bound, 10k+ connections | Async (tokio, asyncio, Loom) |
| CPU-bound, multi-core | Threads / rayon (Rust) |
| Pipeline, multi-stage | Channels (Go, Rust mpsc) |
| Isolation + fault tolerance | Actors (Elixir, Akka) |
| Shared mutable state | Mutex + minimize critical section |
| Hot counter | Atomic, no lock |
**기본값**: structured concurrency + bounded channel + cancellation propagation.
## 🔗 Graph
- 부모: [[Programming Paradigms]] · [[Operating Systems]]
- 변형: [[Async Programming]] · [[Parallelism]]
- 응용: [[Web Servers]] · [[Distributed Systems]]
- Adjacent: [[Race Conditions]] · [[Deadlocks]]
## 🤖 LLM 활용
**언제**: 매 concurrent code review 의 race-condition spotting, 매 deadlock-pattern detection, 매 channel-pattern translation.
**언제 X**: 매 subtle memory-ordering bug — 매 formal verification (TLA+, loom) 의 사용.
## ❌ 안티패턴
- **Shared mutable state without sync**: 매 race condition. UB in C++/Rust.
- **Mutex in hot path**: 매 contention 의 serialization. 매 atomic / per-thread state.
- **Unbounded goroutine spawn**: 매 OOM. 매 bounded pool / semaphore.
- **Sync I/O in async function**: 매 single blocked task → 매 entire executor stall.
- **Lock ordering inconsistent**: 매 deadlock. 매 always same order.
- **Cancellation 의 ignore**: 매 dangling task / resource leak.
## 🧪 검증 / 중복
- Verified (Hoare _Communicating Sequential Processes_, Go Memory Model 2022, Rust Async Book, JEP 444 (Java Virtual Threads), Python PEP 703).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — primitives, Go/Rust/Java/Python pattern, anti-patterns |