from __future__ import annotations

import threading
from collections import deque
from typing import Callable, TypeVar

T = TypeVar("T")


class WriteQueue:
    """全局 raw 写 FIFO — 与 dream_lock 并行，仅串行 atoms append。"""

    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._depth = 0

    @property
    def depth(self) -> int:
        with self._lock:
            return self._depth

    def run(self, fn: Callable[[], T]) -> T:
        with self._lock:
            self._depth += 1
            try:
                return fn()
            finally:
                self._depth -= 1
