Skip to content

Commit

Permalink
opt: improve the buffered channels
Browse files Browse the repository at this point in the history
  • Loading branch information
panjf2000 committed Jan 27, 2021
1 parent fc042cc commit 83b96ed
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
18 changes: 11 additions & 7 deletions gnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,15 +321,19 @@ func sniffErrorAndLog(err error) {
}

// channelBuffer determines whether the channel should be a buffered channel to get the best performance.
func channelBuffer(preset int) int {
var channelBuffer = func() int {
// Use blocking channel if GOMAXPROCS=1.
// This switches context from sender to receiver immediately,
// which results in higher performance (under go1.5 at least).
if runtime.GOMAXPROCS(0) == 1 {
// which results in higher performance.
var n int
if n = runtime.GOMAXPROCS(0); n == 1 {
return 0
}

// Use non-blocking workerChan if GOMAXPROCS>1,
// since otherwise the sender might be dragged down if the receiver is CPU-bound.
return preset
}
// Make channel non-blocking and set up its capacity with GOMAXPROCS if GOMAXPROCS>1,
// otherwise the sender might be dragged down if the receiver is CPU-bound.
//
// GOMAXPROCS determines how many goroutines can run in parallel,
// which makes it the best choice as the channel capacity,
return n
}()
2 changes: 1 addition & 1 deletion server_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ func serve(eventHandler EventHandler, listener *listener, options *Options, prot
}

svr.cond = sync.NewCond(&sync.Mutex{})
svr.ticktock = make(chan time.Duration, channelBuffer(1))
svr.ticktock = make(chan time.Duration, channelBuffer)
svr.logger = logging.DefaultLogger
svr.codec = func() ICodec {
if options.Codec == nil {
Expand Down
7 changes: 1 addition & 6 deletions server_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ import (
"github.com/panjf2000/gnet/internal/logging"
)

// commandBufferSize represents the buffer size of event-loop command channel on Windows.
const (
commandBufferSize = 128
)

var errCloseAllConns = errors.New("close all connections in event-loop")

type server struct {
Expand Down Expand Up @@ -96,7 +91,7 @@ func (svr *server) startListener() {
func (svr *server) startEventLoops(numEventLoop int) {
for i := 0; i < numEventLoop; i++ {
el := new(eventloop)
el.ch = make(chan interface{}, channelBuffer(commandBufferSize))
el.ch = make(chan interface{}, channelBuffer)
el.svr = svr
el.connections = make(map[*stdConn]struct{})
el.eventHandler = svr.eventHandler
Expand Down

0 comments on commit 83b96ed

Please sign in to comment.