Skip to content

fix: replace Windows input busy-poll with WaitForSingleObject#120

Open
tc608 wants to merge 1 commit into
charmbracelet:mainfrom
tc608:fix/windows-idle-cpu-polling
Open

fix: replace Windows input busy-poll with WaitForSingleObject#120
tc608 wants to merge 1 commit into
charmbracelet:mainfrom
tc608:fix/windows-idle-cpu-polling

Conversation

@tc608

@tc608 tc608 commented Jun 8, 2026

Copy link
Copy Markdown

Problem

The Windows streamData implementation in terminal_reader_windows.go uses PeekConsoleInput + time.Sleep(10ms) in a tight loop. Since PeekConsoleInput is non-blocking and returns immediately when no input is available, this creates a 100Hz polling loop even when the TUI application is completely idle.

This causes noticeable CPU usage for all TUI applications on Windows that use ultraviolet for input handling.

Solution

Replace the busy-poll with WaitForSingleObject on the console input handle (conin), which blocks in the kernel until input events are available — zero CPU when idle.

A 1-second timeout ensures cancellation is detected promptly.

Additionally, pre-allocate the peek buffer (peekBuf) and reuse it across iterations via peekNConsoleInputsInto(), eliminating repeated ~80KB allocations per poll cycle.

Changes

  • Replace time.Sleep(10ms) polling with WaitForSingleObject(conin, 1000)
  • Add peekNConsoleInputsInto() to reuse pre-allocated buffer
  • Remove unused "time" import

Impact

Metric Before After
Idle wakeups/sec 100 ≤1
Idle CPU Noticeable ~0%
Input latency ≤10ms Immediate
Cancel detection Immediate ≤1s

Testing

Built and tested on Windows 11. Idle CPU dropped from noticeable usage to 0%.

…dows

The Windows streamData implementation uses PeekConsoleInput + time.Sleep(10ms)
in a tight loop, polling at 100Hz even when idle. This causes noticeable CPU
usage for all TUI applications on Windows.

Replace the busy-poll with WaitForSingleObject on the console input handle,
which blocks in the kernel until input is available (zero CPU). A 1s timeout
ensures cancellation is detected promptly.

Also pre-allocate the peek buffer to avoid repeated 80KB allocations per poll.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant