Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 38 additions & 11 deletions SilKit/source/core/vasio/VAsioPeer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,12 @@ void VAsioPeer::SendSilKitMsgInternal(SendItem item)

lock.unlock();

_ioContext->Dispatch([this] { StartAsyncWrite(); });
// Start the write directly on the calling thread instead of handing it off to the IO thread:
// the stream serializes socket access internally, and asio performs the send() speculatively
// on the calling thread, so only the completion is handled on the IO thread. Avoiding the
// hand-off saves one thread wake-up per message, which dominates latency on busy or
// virtualized hosts.
StartAsyncWrite();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A fundamental design in the SIL Kit it that the sending, receiving and invoking handlers happens on the IO Thread. Main purpose is that

  • the user does not has to think about concurrency of these operations (no locks in handlers)
  • the sequence of sending messages is somehow deterministic (everyone dispatches to the IO Worker)

@KyllianAubry can you say how this is affected by this change.

@KonradBreitsprecherBkd KonradBreitsprecherBkd Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So part of my assumption (and also the code comment) was misleading, this does not alter the threading behavior of sending because at least through the public API SendMsg still goes through VAsioConnection.hpp's ExecuteOnIoThread...

}
}

Expand Down Expand Up @@ -184,23 +189,42 @@ void VAsioPeer::Flush()

void VAsioPeer::StartAsyncWrite()
{
if (_sending)
return;

// May run on any thread: ownership of the single in-flight write is decided under the lock.
std::unique_lock<std::mutex> lock{_sendingQueueMutex};
if (_sendingQueue.empty())
if (_sending || _sendingQueue.empty())
{
return;
}

_sending = true;

_currentSendItem = std::move(_sendingQueue.front());
_sendingQueue.pop_front();
lock.unlock();
while (true)
{
_currentSendItem = std::move(_sendingQueue.front());
_sendingQueue.pop_front();
lock.unlock();

_currentSendingBuffer = ConstBuffer(_currentSendItem.data.data(), _currentSendItem.data.size());

// Common case: the kernel accepts the whole message right away, so no IO-thread round trip
// (neither to start the write nor to process its completion) is needed.
const auto written = _socket->TryWriteSome(ConstBufferSequence{&_currentSendingBuffer, 1});
if (written < _currentSendingBuffer.GetSize())
{
_currentSendingBuffer.SliceOff(written);
WriteSomeAsync();
return;
}

_currentSendingBuffer = ConstBuffer(_currentSendItem.data.data(), _currentSendItem.data.size());
WriteSomeAsync();
_currentSendItem.transmitReservation.reset();

lock.lock();
if (_sendingQueue.empty())
{
_sending = false;
return;
}
}
}

void VAsioPeer::WriteSomeAsync()
Expand Down Expand Up @@ -332,7 +356,10 @@ void VAsioPeer::OnAsyncWriteSomeDone(IRawByteStream& stream, size_t bytesTransfe
}

_currentSendItem.transmitReservation.reset();
_sending = false;
{
std::unique_lock<std::mutex> lock{_sendingQueueMutex};
_sending = false;
}
StartAsyncWrite();
}

Expand Down
4 changes: 4 additions & 0 deletions SilKit/source/core/vasio/io/IRawByteStream.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ struct IRawByteStream

virtual void AsyncWriteSome(ConstBufferSequence bufferSequence) = 0;

//! Writes as much as possible without blocking, from any thread, if no asynchronous write is in
//! progress. Returns the number of bytes written; 0 means the caller must use AsyncWriteSome.
virtual auto TryWriteSome(ConstBufferSequence bufferSequence) -> size_t = 0;

virtual void Shutdown() = 0;
};

Expand Down
28 changes: 28 additions & 0 deletions SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,34 @@ void AsioGenericRawByteStream::AsyncWriteSome(ConstBufferSequence bufferSequence
}


auto AsioGenericRawByteStream::TryWriteSome(ConstBufferSequence bufferSequence) -> size_t
{
#if defined(__linux__)
std::unique_lock<decltype(_mutex)> lock{_mutex};

if (_shutdownPending || _writing || bufferSequence.size() != 1)
{
return 0;
}

// Bypasses asio's socket object on purpose: a plain non-blocking send() on the descriptor does not
// touch asio's per-socket state, so it cannot race with the asynchronous read pending on the IO
// thread, and it completes without posting a completion handler (i.e. without waking the IO thread).
const auto& buffer = bufferSequence.data()[0];
const auto result = ::send(_socket.native_handle(), buffer.GetData(), buffer.GetSize(), MSG_DONTWAIT | MSG_NOSIGNAL);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asio already sets non_blocking on the socket, no? MSG_DONTWAIT doesnt add anything, except making this non-portable (i think FreeBSD and macos has that, too). but the MSG_NOSIGNAL is definitely not portable (SO_NOSIGPIPE in bsd) ...
So TryWriteSome is returning 0 on most platforms -- impossible to unit-test this.

we should use the asio builtins instead of raw syscalls, and flip the #ifdef to ignore windows:
Call _socket.non_blocking(true) once.
Then call _socket.write_some(buf, ec) and return 0 on asio::error::would_block.

if (result < 0)
{
// EAGAIN as well as real errors: let the asynchronous path wait for writability or report the error.
return 0;
}
return static_cast<size_t>(result);
#else
SILKIT_UNUSED_ARG(bufferSequence);
return 0;
#endif
}


void AsioGenericRawByteStream::Shutdown()
{
SILKIT_TRACE_METHOD_(_logger, "()");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ class AsioGenericRawByteStream final : public IRawByteStream
auto GetRemoteEndpoint() const -> std::string override;
void AsyncReadSome(MutableBufferSequence bufferSequence) override;
void AsyncWriteSome(ConstBufferSequence bufferSequence) override;
auto TryWriteSome(ConstBufferSequence bufferSequence) -> size_t override;
void Shutdown() override;

private:
Expand Down
5 changes: 5 additions & 0 deletions SilKit/source/core/vasio/io/mock/MockRawByteStream.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ struct MockRawByteStream : IRawByteStream
MOCK_METHOD(void, SetListener, (IRawByteStreamListener&), (override));
MOCK_METHOD(void, AsyncReadSome, (MutableBufferSequence), (override));
MOCK_METHOD(void, AsyncWriteSome, (ConstBufferSequence), (override));
// Always defer to AsyncWriteSome, so existing expectations on the asynchronous path still hold.
auto TryWriteSome(ConstBufferSequence) -> size_t override
{
return 0;
}
MOCK_METHOD(void, Shutdown, (), (override));
};

Expand Down