Skip to content

A NBChannel is a non-blocking channel. Normal Crystal channels block on send and on receive. The NBChannel will never block on send, and there are both blocking and nonblocking receive calls available. The channel should work both for single producer, single consumer scenarios, and for scenarios with multiple producers or multiple consumers.

License

Notifications You must be signed in to change notification settings

wyhaines/nbchannel.cr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

nbchannel

Send.cr CI GitHub release GitHub commits since latest release (by SemVer)

This is a subclass of the standard Crystal Channel to make it into a non-blocking Channel implementation. The normal Crystal Channel blocks on receive, and on send if the channel the channel has no buffer, or if the fixed-size buffer is full. This non-blocking channel implementation makes it possible to send and receive messages asynchronously, with no blocking on either receive or send.

Installation

  1. Add the dependency to your shard.yml:

    dependencies:
      nbchannel:
        github: wyhaines/nbchannel.cr
  2. Run shards install

Usage

require "nbchannel"

An instance of NBChannel is created in almost exactly the same way as standard Crystal Channel. The only difference is that an NBChannel has infinite capacity, so there is no capacity argument to #new.

channel = NBChannel(String).new

Once created, any Fiber/Thread should be able to #send to an NBChannel without ever blocking on the send.

channel.send("I am a message.")

Messages can be received from a channel in a blocking or a nonblocking manner.

channel = NBChannel(String).new
spawn channel.send("I am a message.")
msg = channel.receive # This will block until a message is sent.
channel = NBChannel(String).new
spawn do
  x = rand.seconds * 1.0
  puts "sleeping #{x}"
  sleep x
  channel.send("Gotcha!")
end

y = rand.seconds
puts "waiting #{y}"
sleep y

puts channel.receive? || "You escaped the trap!"

Contributing

  1. Fork it (https://github.com/wyhaines/nbchannel/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

GitHub code size in bytes GitHub issues

About

A NBChannel is a non-blocking channel. Normal Crystal channels block on send and on receive. The NBChannel will never block on send, and there are both blocking and nonblocking receive calls available. The channel should work both for single producer, single consumer scenarios, and for scenarios with multiple producers or multiple consumers.

Resources

License

Stars

Watchers

Forks

Packages

No packages published