Skip to content

[libc] Use file lock to join newline on RPC puts call #73373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 27, 2023
Merged

Conversation

jhuber6
Copy link
Contributor

@jhuber6 jhuber6 commented Nov 24, 2023

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.

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.
@llvmbot llvmbot added the libc label Nov 24, 2023
@llvmbot
Copy link
Member

llvmbot commented Nov 24, 2023

@llvm/pr-subscribers-libc

Author: Joseph Huber (jhuber6)

Changes

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.


Full diff: https://github.com/llvm/llvm-project/pull/73373.diff

1 Files Affected:

  • (modified) libc/utils/gpu/server/rpc_server.cpp (+4-2)
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;

@jhuber6 jhuber6 merged commit bf02c84 into llvm:main Nov 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants