9148c358d0
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
191 lines
5.6 KiB
Markdown
191 lines
5.6 KiB
Markdown
---
|
|
id: wiki-2026-0508-concurrent-programming
|
|
title: Concurrent Programming
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Concurrency, Multithreading, Async Programming]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [programming, concurrency, parallelism, systems]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: Go, Rust, Python, JavaScript
|
|
framework: tokio, asyncio, goroutines
|
|
---
|
|
|
|
# Concurrent Programming
|
|
|
|
## 매 한 줄
|
|
> **"매 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.
|
|
|
|
## 매 핵심
|
|
|
|
### 매 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.
|
|
|
|
### 매 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.
|
|
|
|
### 매 응용
|
|
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).
|
|
|
|
## 💻 패턴
|
|
|
|
### Go: goroutine + channel
|
|
```go
|
|
package main
|
|
|
|
import "fmt"
|
|
|
|
func worker(id int, jobs <-chan int, results chan<- int) {
|
|
for j := range jobs {
|
|
results <- j * 2
|
|
}
|
|
fmt.Println("worker", id, "done")
|
|
}
|
|
|
|
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 }
|
|
}
|
|
```
|
|
|
|
### Rust: tokio + select!
|
|
```rust
|
|
use tokio::{select, time::{sleep, Duration}};
|
|
|
|
#[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}"),
|
|
}
|
|
}
|
|
```
|
|
|
|
### 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
|
|
```
|
|
|
|
### Python: asyncio TaskGroup (3.11+)
|
|
```python
|
|
import asyncio
|
|
import httpx
|
|
|
|
async def fetch(client, url):
|
|
r = await client.get(url)
|
|
return r.status_code
|
|
|
|
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
|
|
- 변형: [[Async Programming]]
|
|
- 응용: [[Distributed Systems]]
|
|
|
|
## 🤖 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 |
|