Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Chan ¶
type Chan interface { // Empty reports whether a read from a channel would block (that is, the channel is empty). Empty() bool // Closed returns true if a channel is closed. Closed() bool // Locked is true if channel lock is active. // // Lock is active when any write operation is performed on a channel at the same goroutine. // // See: https://github.com/golang/go/blob/master/src/runtime/chan.go#L52 Locked() bool // Data returns a pointer to a channel buffer. Data() unsafe.Pointer // Pointer returns a raw pointer to underlying channel structure. Pointer() unsafe.Pointer // Len returns a number of elements in a channel buffer. Len() int // Cap returns a size of a channel buffer. Cap() int }
func ValueOf ¶
ValueOf returns a Chan instance for a given channel.
Second argument sync controls whether channel operations should lock a channel. Please note that locking a channel may cause a deadlock if the channel is used.
Example ¶
package main import ( "fmt" "github.com/x1unix/chanspy" ) func main() { // Simple case with immediate access. // May cause race condition if the channel is used for read/write atm. ch := make(chan int, 10) ch <- 1 ch <- 2 ch <- 3 ch <- 4 defer close(ch) // c.Locked() will be true as channel has active write operation in this goroutine. c := chanspy.ValueOf(ch) fmt.Printf( "Regular: IsClosed=%t Locked=%t Len=%d Cap=%d\n", c.Closed(), c.Locked(), c.Len(), c.Cap(), ) // Thread-safe access. // Will try to lock a channel before performing any operations. // Useful for concurrent access. done := make(chan struct{}) go func() { // c.Locked() is false as we're in a different goroutine. c := chanspy.ValueOf(ch, chanspy.WithLock) _ = <-ch _ = <-ch fmt.Printf( "WithLock: IsClosed=%t Locked=%t Len=%d Cap=%d\n", c.Closed(), c.Locked(), c.Len(), c.Cap(), ) done <- struct{}{} }() <-done }
Output: Regular: IsClosed=false Locked=true Len=4 Cap=10 WithLock: IsClosed=false Locked=false Len=2 Cap=10
Click to show internal directories.
Click to hide internal directories.