rchan

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 16, 2023 License: MIT Imports: 5 Imported by: 1

README

GoDoc

rchan

ResponseChan, a simple method to get a uint64 value for a channel that can be used to receive a later response.

This can be used alongside time.Time to send requests to an async peer and connect responses back.

usage

On one side:

	id, ch := rchan.New()
	defer id.Release() // it is important to release the id after use
	sendRequest(id, ...) // will send the request via rpc/etc, response is expected to come back through a different channel

	select {
	case res <- ch:
		// got a response!
		return res, nil
	case <-ctx.Done():
		// expired
		return nil, ctx.Err()
	}

And another side receiving the response from the IPC/etc:

	id := rchan.Id(response.id)
	id.SendTimeout(100*time.Millisecond, response.data) // this will safely send the response to the recipient, other methods are also available

Note that the sending side should always have a timeout in order to avoid deadlocks from a race condition happening between the time when read times out and the channel is released. Go's chan structure provides no good way to deal with this, as for example closing the channel will cause writes to panic without providing a way to check for exceptions.

This could be avoided by using a more complex structure but the goal of this library is to provide the lightest possible way to use go channels. This race condition case is unlikely enough so that a timeout will most likely work.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrChanClosed = errors.New("This channel has already been closed")
)

Functions

This section is empty.

Types

type Id

type Id uint64

func New

func New() (Id, <-chan any)

New creates a new rchan and returns the associated chan to read from to obtain the delayed response.

func (Id) C

func (r Id) C() chan<- any

C will return the channel associated with a rchan object, or nil, and can be used to send the response to the initiator

func (Id) Release

func (r Id) Release()

Release will release the given object from memory, future calls to C() on this object will return nil.

func (*Id) Send

func (r *Id) Send(ctx context.Context, v any) error

Send will send the given value in the given channel unless the context expires first

func (*Id) SendTimeout

func (r *Id) SendTimeout(max time.Duration, v any) error

SendTimeout will perform a send that will expire after a given time, using a timer rather than contexts in order to limit weight

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL