github.com/annchain/OG@v0.0.9/ffchan/ffchan.go (about) 1 // Copyright © 2019 Annchain Authors <EMAIL ADDRESS> 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package ffchan 15 16 import ( 17 "github.com/annchain/OG/arefactor/common/goroutine" 18 "github.com/sirupsen/logrus" 19 "reflect" 20 "runtime/debug" 21 "time" 22 ) 23 24 type TimeoutSender struct { 25 channel interface{} 26 val interface{} 27 groupName string 28 timeout time.Duration 29 C chan bool 30 } 31 32 func NewTimeoutSenderShort(channel interface{}, val interface{}, groupName string) *TimeoutSender { 33 return NewTimeoutSender(channel, val, groupName, 5000) 34 } 35 36 func NewTimeoutSender(channel interface{}, val interface{}, groupName string, timeoutMs int) *TimeoutSender { 37 t := &TimeoutSender{ 38 groupName: groupName, 39 channel: channel, 40 timeout: time.Millisecond * time.Duration(timeoutMs), 41 val: val, 42 C: make(chan bool), 43 } 44 c := make(chan struct{}) 45 goroutine.New(func() { 46 defer close(c) 47 vChan := reflect.ValueOf(t.channel) 48 vVal := reflect.ValueOf(t.val) 49 vChan.Send(vVal) 50 }) 51 52 goroutine.New(func() { 53 start := time.Now() 54 loop: 55 for { 56 select { 57 case <-c: 58 t.C <- true 59 break loop 60 case <-time.After(t.timeout): 61 logrus.WithField("chan", t.groupName). 62 WithField("val", t.val). 63 WithField("elapse", time.Now().Sub(start)). 64 Warn("Timeout on channel writing. Potential block issue.") 65 debug.PrintStack() 66 if t.timeout < time.Second { 67 time.Sleep(time.Second) 68 } 69 } 70 } 71 }) 72 73 return t 74 }