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 폴더 제거.
6.0 KiB
6.0 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-resource-management | Resource Management | 10_Wiki/Topics | verified | self |
|
none | A | 0.9 | applied |
|
2026-05-10 | pending |
|
Resource Management
매 한 줄
"매 acquire/release 의 pairing 을 lexical scope 에 강제". 매 file handle, socket, mutex, GPU buffer, DB connection 등 finite resource 의 leak 을 방지하는 discipline. Stroustrup 의 RAII (1980s C++) → Rust 의 ownership/Drop (2015) → Python
with/ Java try-with-resources / TSusing(TC39 Stage 3, 2023) 으로 mainstream language 전반에 확산.
매 핵심
매 resource 종류
- Memory: heap allocation, buffer, arena.
- Handles: file, socket, pipe, FD limit (Linux 기본 1024).
- Locks: mutex, rwlock, semaphore, distributed lock (Redis/etcd).
- Connections: DB pool, HTTP keep-alive, gRPC channel.
- GPU/Accelerator: VRAM buffer, CUDA stream, MLX array.
매 acquire/release 패턴
- RAII: ctor acquire, dtor release — C++/Rust.
- try-with-resources: lexical block — Java/Python/TS
using. - Defer: stack-of-callbacks — Go, Zig.
- Linear types: compile-time use-once — Rust ownership, Haskell linear.
매 응용
- Connection pool: max_size + idle timeout + acquire timeout.
- Bounded concurrency: semaphore 로 N parallel limit.
- Cleanup ordering: LIFO (stack) — dependent resource 먼저 release.
💻 패턴
Rust: RAII via Drop
use std::fs::File;
use std::io::Write;
fn write_log(msg: &str) -> std::io::Result<()> {
let mut f = File::create("/tmp/log.txt")?; // acquire
f.write_all(msg.as_bytes())?;
Ok(()) // f.drop() automatic — release on scope exit, even on panic
}
TypeScript: using (TC39 explicit resource management, ES2024)
class DbConnection implements Disposable {
constructor(public readonly url: string) { /* connect */ }
query(sql: string) { /* ... */ }
[Symbol.dispose]() { /* close */ }
}
function fetchUser(id: string) {
using db = new DbConnection('postgres://...');
return db.query(`select * from users where id='${id}'`);
} // db disposed automatically on return / throw
Python: contextmanager
from contextlib import contextmanager
import psycopg
@contextmanager
def connection(dsn: str):
conn = psycopg.connect(dsn)
try:
yield conn
finally:
conn.close()
with connection('postgres://...') as c:
c.execute('SELECT 1')
# c is closed even if execute raises
Go: defer (LIFO)
func processFile(path string) error {
f, err := os.Open(path)
if err != nil { return err }
defer f.Close() // LIFO — runs even on panic
lock := acquireLock()
defer lock.Release()
return parse(f)
}
Connection pool (Node + pg)
import { Pool } from 'pg';
const pool = new Pool({
max: 20,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 2_000,
});
async function getUser(id: string) {
const client = await pool.connect();
try {
const r = await client.query('SELECT * FROM users WHERE id=$1', [id]);
return r.rows[0];
} finally {
client.release(); // 매 finally 가 critical
}
}
Bounded concurrency (semaphore)
import pLimit from 'p-limit';
const limit = pLimit(10); // max 10 concurrent
const results = await Promise.all(
urls.map(url => limit(() => fetch(url).then(r => r.json()))),
);
MLX GPU buffer (Apple Silicon, 2026)
import mlx.core as mx
def process_batch(x: mx.array) -> mx.array:
# MLX uses unified memory; explicit eval boundaries
y = mx.matmul(x, x.T)
mx.eval(y) # force materialization, release lazy graph
return y
AsyncIO timeout + cancel
import asyncio
async def fetch_with_timeout():
async with asyncio.timeout(5.0):
async with aiohttp.ClientSession() as s:
async with s.get('https://api.example.com') as r:
return await r.json()
# all three context managers cleanly close on timeout
매 결정 기준
| 상황 | Approach |
|---|---|
| Rust/C++ | RAII via Drop/destructor (default) |
| TS/JS modern | using + Disposable (TC39 explicit) |
| Python | with + contextlib |
| Go | defer (LIFO ordering) |
| Network connection 다수 | Pool + acquire timeout |
| Concurrent task 수천 | Semaphore (p-limit, asyncio.Semaphore) |
| GPU memory | Explicit eval / del / cudaFree |
기본값: 매 lexical scope 기반 (RAII / using / with / defer). 매 manual close 의 X.
🔗 Graph
- 부모: Concurrency
- 변형: RAII
- 응용: Memory Management · Graceful Shutdown
- Adjacent: Error Handling · Async Programming · Garbage Collection
🤖 LLM 활용
언제: 매 server, 매 batch job, 매 GPU inference, 매 long-running daemon — 매 leak 누적이 critical. 언제 X: 매 short-lived script (<1s), 매 throwaway notebook — 매 process exit 이 cleanup.
❌ 안티패턴
- Forgotten close: 매 try 만, 매 finally 없음 → leak on exception.
- Double-free: 매 close 두 번 → undefined behavior 또는 exception.
- Use-after-release: 매 closed connection 재사용 → broken pipe.
- Manual ref counting in GC language: 매 reinventing —
using/with사용. - Unbounded pool: 매 max 없음 → DB connection storm 으로 outage.
- GPU OOM 무시: 매 eval 없이 lazy graph 누적 → MLX/CUDA OOM.
🧪 검증 / 중복
- Verified: Stroustrup The C++ Programming Language; Rust Programming Rust 2e; TC39 Explicit Resource Management proposal (Stage 3, 2024).
- 신뢰도 A.
🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — RAII/using/with/defer patterns + pooling + GPU |