您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關如何在golang項目中實現一個等待觸發事件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
type Wait interface { // Register waits returns a chan that waits on the given ID. // The chan will be triggered when Trigger is called with // the same ID. Register(id uint64) <-chan interface{} // Trigger triggers the waiting chans with the given ID. Trigger(id uint64, x interface{}) IsRegistered(id uint64) bool } type list struct { l sync.RWMutex m map[uint64]chan interface{} } func Newlist() Wait { return &list{m : make(map[uint64]chan interface{})} } //注冊 func (w *list) Register(id uint64) <-chan interface{} { w.l.Lock() defer w.l.Unlock() ch := w.m[id] if ch != nil { log.Fatal("dup id error") return nil } ch = make(chan interface{},1) w.m[id] = ch return ch } //觸發 func (w *list) Trigger(id uint64, x interface{}) { w.l.Lock() ch := w.m[id] delete(w.m,id) w.l.Unlock() if ch != nil { ch <- x close(ch) } } //判斷該id是否被注冊 func (w *list) IsRegistered(id uint64) bool { w.l.RLock() defer w.l.Unlock() _,ok := w.m[id] return ok }
示例
var timeOutDuration = time.Minute*10 func main() { list := Newlist() rid := uint64(time.Now().UnixNano()) go func() { ch := list.Register(rid) fmt.Println("start register:",rid) if ch == nil { return } select { case x := <- ch: fmt.Printf("trigger over id:%d,x:%v\n",rid,x) case <-time.After(timeOutDuration): log.Println("timeout error:",rid) } }() time.Sleep(time.Second) rid2 := uint64(time.Now().UnixNano()) go func() { ch := list.Register(rid2) fmt.Println("start register:",rid2) if ch == nil { return } select { case x := <- ch: fmt.Printf("trigger over id:%d,x:%v\n",rid2,x) case <-time.After(timeOutDuration): log.Println("timeout error:",rid2) } }() go func() { time.Sleep(time.Second*5) list.Trigger(rid,"Hello") time.Sleep(time.Second*3) list.Trigger(rid2,"World") }() select { } }
補充:GO 程序等待一段時間執行
我就廢話不多說了,大家還是直接看代碼吧~
package main import ( "fmt" "time" ) func main() { fmt.Println(time.Now()) //等1秒 time.Sleep(time.Second * 1) fmt.Println(time.Now()) //等1秒 <-time.After(time.Second * 1) fmt.Println(time.Now()) }
看完上述內容,你們對如何在golang項目中實現一個等待觸發事件有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。