serve: the stdin reader shares its state with main instead of borrowing main's locals (QUIT race)

The stdin reader thread is detached and captured main's stop flag, mutex, condition variable,
line queue and EOF flag by reference. The server writes QUIT and closes stdin right after it,
so the reader often wakes with EOF while main is returning: it then locked a destroyed mutex
and wrote to a destroyed deque (undefined behaviour on every platform; the Metal port aborted
on it). The state now lives in a shared_ptr that the thread holds a copy of, so it outlives
main's frame for as long as the reader runs. CUDA/HIP and SYCL engines alike; no change to
what the engine reads or answers.
This commit is contained in:
Niko1221 committed 2026-10-13 00:28:26 +02:00
1 parent f5082f41a6
commit 6339e8610d
2 files changed
+48 -26

No files matched your search

+24 -13
View File
@@ -9042,12 +9042,23 @@ int main(int argc, char** argv) {
};
// stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went
// away, or pressed Esc): the flag is checked between prompt chunks and between verify windows.
std::atomic<bool> stop_req{false};
std::mutex in_mu;
std::condition_variable in_cv;
std::deque<std::string> in_lines;
bool in_eof = false;
std::thread([&] {
// 0.1.44: the reader is detached and may sit in read(2) past QUIT (the server writes more, or closes stdin, while
// main returns and the process exits), so what it touches is shared with it, never main's locals: a line or
// EOF after QUIT used to lock a destroyed mutex (undefined behaviour; an abort on macOS).
struct StdinShared {
std::atomic<bool> stop_req{false};
std::mutex mu;
std::condition_variable cv;
std::deque<std::string> lines;
bool eof = false;
};
const auto in_shared = std::make_shared<StdinShared>();
std::atomic<bool>& stop_req = in_shared->stop_req;
std::mutex& in_mu = in_shared->mu;
std::condition_variable& in_cv = in_shared->cv;
std::deque<std::string>& in_lines = in_shared->lines;
bool& in_eof = in_shared->eof;
std::thread([st = in_shared] {
strata::aux_cpus::pin_current_thread();
// read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for
// stdin's lock, which getline holds while it waits for input - an engine ending on an error (every
@@ -9079,14 +9090,14 @@ int main(int argc, char** argv) {
};
while (getline_fd(l)) {
if (!l.empty() && l.back() == '\r') l.pop_back();
if (l == "STOP") { stop_req.store(true); continue; }
std::lock_guard<std::mutex> lk(in_mu);
in_lines.push_back(l);
in_cv.notify_one();
if (l == "STOP") { st->stop_req.store(true); continue; }
std::lock_guard<std::mutex> lk(st->mu);
st->lines.push_back(l);
st->cv.notify_one();
}
std::lock_guard<std::mutex> lk(in_mu);
in_eof = true;
in_cv.notify_one();
std::lock_guard<std::mutex> lk(st->mu);
st->eof = true;
st->cv.notify_one();
}).detach();
auto next_line = [&](std::string& out) -> bool {
std::unique_lock<std::mutex> lk(in_mu);