Files
2nd/10_Wiki/Topics/Other/Concurrent Programming.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

5.6 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-concurrent-programming Concurrent Programming 10_Wiki/Topics verified self
Concurrency
Multithreading
Async Programming
none A 0.9 applied
programming
concurrency
parallelism
systems
2026-05-10 pending
language framework
Go, Rust, Python, JavaScript 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

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!

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

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+)

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)

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

use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);

fn bump() -> u64 {
    COUNTER.fetch_add(1, Ordering::Relaxed)
}

Actor pattern (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

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

🤖 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