Skip to content

Commit

Permalink
Merge pull request #23 from gogf/master
Browse files Browse the repository at this point in the history
bug更新
  • Loading branch information
jroam committed Jun 12, 2019
2 parents 211e06d + 905d5ab commit e2070e7
Show file tree
Hide file tree
Showing 3 changed files with 363 additions and 19 deletions.
44 changes: 25 additions & 19 deletions g/container/gchan/gchan.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,55 +10,61 @@
package gchan

import (
"errors"
"github.com/gogf/gf/g/container/gtype"
"errors"

"github.com/gogf/gf/g/container/gtype"
)

// Graceful channel.
type Chan struct {
channel chan interface{}
closed *gtype.Bool
channel chan interface{}
closed *gtype.Bool
}

// New creates a graceful channel with given <limit>.
func New(limit int) *Chan {
return &Chan {
channel : make(chan interface{}, limit),
closed : gtype.NewBool(),
}
return &Chan{
channel: make(chan interface{}, limit),
closed: gtype.NewBool(),
}
}

// Push pushes <value> to channel.
// It is safe to be called repeatedly.
func (c *Chan) Push(value interface{}) error {
if c.closed.Val() {
return errors.New("channel is closed")
}
c.channel <- value
return nil
if c.closed.Val() {
return errors.New("channel is closed")
}
c.channel <- value
return nil
}

// Pop pops value from channel.
// If there's no value in channel, it would block to wait.
// If the channel is closed, it will return a nil value immediately.
func (c *Chan) Pop() interface{} {
return <- c.channel
return <-c.channel
}

// Close closes the channel.
// It is safe to be called repeatedly.
func (c *Chan) Close() {
if !c.closed.Set(true) {
close(c.channel)
}
if !c.closed.Set(true) {
close(c.channel)
}
}

// See Len.
func (c *Chan) Size() int {
return c.Len()
return c.Len()
}

// Len returns the length of the channel.
func (c *Chan) Len() int {
return len(c.channel)
}
}

// Cap returns the capacity of the channel.
func (c *Chan) Cap() int {
return cap(c.channel)
}
47 changes: 47 additions & 0 deletions g/container/gchan/gchan_z_unit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package gchan_test

import (
"errors"
"testing"

"github.com/gogf/gf/g/container/gchan"
"github.com/gogf/gf/g/test/gtest"
)

func Test_Gchan(t *testing.T) {
gtest.Case(t, func() {
ch := gchan.New(10)

gtest.Assert(ch.Cap(), 10)
gtest.Assert(ch.Push(1), nil)
gtest.Assert(ch.Len(), 1)
gtest.Assert(ch.Size(), 1)
ch.Pop()
gtest.Assert(ch.Len(), 0)
gtest.Assert(ch.Size(), 0)
ch.Close()
gtest.Assert(ch.Push(1), errors.New("channel is closed"))

ch = gchan.New(0)
ch1 := gchan.New(0)
go func() {
var i = 0
for {
v := ch.Pop()
if v == nil {
ch1.Push(i)
break
}
gtest.Assert(v, i)
i++
}
}()

for index := 0; index < 10; index++ {
ch.Push(index)
}
ch.Close()
gtest.Assert(ch1.Pop(), 10)
ch1.Close()
})
}
Loading

0 comments on commit e2070e7

Please sign in to comment.