BidiBuffer is a thread-safe Buffer which can receive data from any thread.
It uses a dual-buffer strategy with mutex protection:
-
+@buffer+ is the main buffer, protected by +@buffer_mutex+
-
+@oob_buffer+ receives data when +@buffer_mutex+ is contended
This allows non-blocking writes from any thread while maintaining thread safety.
Public Class methods
new(*)
[show source]
# File lib/httpx/plugins/stream_bidi.rb 102 def initialize(*) 103 super 104 @buffer_mutex = Thread::Mutex.new 105 @oob_mutex = Thread::Mutex.new 106 @oob_buffer = "".b 107 end
Public Instance methods
<<(chunk)
buffers the chunk to be sent (thread-safe, non-blocking)
[show source]
# File lib/httpx/plugins/stream_bidi.rb 110 def <<(chunk) 111 if @buffer_mutex.try_lock 112 begin 113 super 114 ensure 115 @buffer_mutex.unlock 116 end 117 else 118 # another thread holds the lock, use OOB buffer to avoid blocking 119 @oob_mutex.synchronize { @oob_buffer << chunk } 120 end 121 end
rebuffer()
reconciles the main and secondary buffer (thread-safe, callable from any thread).
[show source]
# File lib/httpx/plugins/stream_bidi.rb 124 def rebuffer 125 @buffer_mutex.synchronize do 126 @oob_mutex.synchronize do 127 return if @oob_buffer.empty? 128 129 @buffer << @oob_buffer 130 @oob_buffer.clear 131 end 132 end 133 end