Skip to content

Commit

Permalink
feature: invoke function in main logic goroutine
Browse files Browse the repository at this point in the history
  • Loading branch information
lonng committed Oct 30, 2017
1 parent ca8c936 commit 8c340c6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
18 changes: 18 additions & 0 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (

// Unhandled message buffer size
const packetBacklog = 1024
const funcBacklog = 1 << 8

var (
// handler service singleton
Expand Down Expand Up @@ -72,6 +73,7 @@ type (
handlers map[string]*component.Handler // all handler method
chLocalProcess chan unhandledMessage // packets that process locally
chCloseSession chan *session.Session // closed session
chFunction chan func() // function that called in logic gorontine
}

unhandledMessage struct {
Expand All @@ -88,6 +90,7 @@ func newHandlerService() *handlerService {
handlers: make(map[string]*component.Handler),
chLocalProcess: make(chan unhandledMessage, packetBacklog),
chCloseSession: make(chan *session.Session, packetBacklog),
chFunction: make(chan func(), funcBacklog),
}

return h
Expand All @@ -109,6 +112,18 @@ func pcall(method reflect.Method, args []reflect.Value) {
}
}

// call handler with protected
func pinvoke(fn func()) {
defer func() {
if err := recover(); err != nil {
logger.Println(fmt.Sprintf("nano/invoke: %v", err))
println(stack())
}
}()

fn()
}

func onSessionClosed(s *session.Session) {
defer func() {
if err := recover(); err != nil {
Expand Down Expand Up @@ -148,6 +163,9 @@ func (h *handlerService) dispatch() {
case s := <-h.chCloseSession: // session closed callback
onSessionClosed(s)

case fn := <-h.chFunction:
pinvoke(fn)

case <-globalTicker.C: // execute cron task
cron()

Expand Down
6 changes: 6 additions & 0 deletions invoke.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package nano

// Invoke invokes function in main logic goroutine
func Invoke(fn func()) {
handler.chFunction <- fn
}
2 changes: 1 addition & 1 deletion timer.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const (

var (
// default timer backlog
timerBacklog = 128
timerBacklog = 1 << 8

// timerManager manager for all timers
timerManager = &struct {
Expand Down

0 comments on commit 8c340c6

Please sign in to comment.