Class: ConcurrentSHM::Channel::Unbuffered::Variable

Inherits:
ConcurrentSHM::Channel::Unbuffered show all
Defined in:
lib/concurrent-shm/channel.rb

Overview

An unbuffered channel with variable-width packets.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ConcurrentSHM::Channel

#close

Class Method Details

.new(shm, capacity:, offset: 0, autosize: true) ⇒ Object

Allocates an unbuffered, variable-width channel with the specified capacity.

Raises:

  • (RangeError)

    if the capacity is less than 1 or greater than 2<sup>32</sup>-1

See Also:



82
83
84
85
86
87
88
89
90
91
92
# File 'lib/concurrent-shm/channel.rb', line 82

def self.new(shm, capacity:, offset: 0, autosize: true)
  raise RangeError, "Capacity must be > 0" unless capacity > 0
  cbytes = bytes_for(capacity) { raise RangeError, "Capacity must be less than 2^32" }

  alloc(shm, cbytes + 2 + capacity, offset: offset, autosize: autosize) do |body|
    @width = body[0, cbytes].as_uintptr
    @state = body[cbytes].as_intptr
    @closed = body[cbytes+1].as_intptr
    @data = body[cbytes+2..]
  end
end

Instance Method Details

#recvString

Receive a variable-width packet over the channel. Blocks if there are no senders.

Returns:

  • (String)

    the packet



110
111
112
113
114
115
116
# File 'lib/concurrent-shm/channel.rb', line 110

def recv
  do_recv do
    w = @width[] - 1
    @width[] = 0
    @data[0...w].read
  end
end

#send(data) ⇒ nil

Send a variable-width packet over the channel. Blocks if there are no receivers.

Parameters:

  • data (String)

    the packet

Returns:

  • (nil)

Raises:

  • (ClosedWriteError)

    if the channel is closed

  • (RangeError)

    if the packet size exceeds the channel capacity



99
100
101
102
103
104
105
106
# File 'lib/concurrent-shm/channel.rb', line 99

def send(data)
  raise RangeError, "Data is wider than channel" if data.size > @data.size

  do_send do
    @width[] = data.bytesize + 1
    @data.write(data)
  end
end