[libc-commits] [libc] [libc] Use file lock to join newline on RPC puts call (PR #73373)

Joseph Huber via libc-commits libc-commits at lists.llvm.org
Fri Nov 24 13:53:48 PST 2023


https://github.com/jhuber6 created https://github.com/llvm/llvm-project/pull/73373

Summary:
The puts call appends a newline. With multiple threads, this can be done
out of order such that another thread puts something before we finish
appending the newline. Add a flockfile and funlockfile to ensure that
the whole string is printed before another string can appear.


>From 1ad8bc747c76668f1eccd6df9c8f1342490da175 Mon Sep 17 00:00:00 2001
From: Joseph Huber <huberjn at outlook.com>
Date: Fri, 24 Nov 2023 15:50:53 -0600
Subject: [PATCH] [libc] Use file lock to join newline on RPC puts call

Summary:
The puts call appends a newline. With multiple threads, this can be done
out of order such that another thread puts something before we finish
appending the newline. Add a flockfile and funlockfile to ensure that
the whole string is printed before another string can appear.
---
 libc/utils/gpu/server/rpc_server.cpp | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/libc/utils/gpu/server/rpc_server.cpp b/libc/utils/gpu/server/rpc_server.cpp
index 05e900edc6993bb..a2e5d0fd5a833f6 100644
--- a/libc/utils/gpu/server/rpc_server.cpp
+++ b/libc/utils/gpu/server/rpc_server.cpp
@@ -78,10 +78,12 @@ struct Server {
 
       port->recv_n(strs, sizes, [&](uint64_t size) { return new char[size]; });
       port->send([&](rpc::Buffer *buffer, uint32_t id) {
-        buffer->data[0] = fwrite(strs[id], 1, sizes[id], files[id]);
+        flockfile(files[id]);
+        buffer->data[0] = fwrite_unlocked(strs[id], 1, sizes[id], files[id]);
         if (port->get_opcode() == RPC_WRITE_TO_STDOUT_NEWLINE &&
             buffer->data[0] == sizes[id])
-          buffer->data[0] += fwrite("\n", 1, 1, files[id]);
+          buffer->data[0] += fwrite_unlocked("\n", 1, 1, files[id]);
+        funlockfile(files[id]);
         delete[] reinterpret_cast<uint8_t *>(strs[id]);
       });
       break;



More information about the libc-commits mailing list