欢迎来到代码驿站!

Golang

当前位置:首页 > 脚本语言 > Golang

golang等待触发事件的实例

时间:2021-07-16 10:41:38|栏目: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())
}

上一篇:在Linux系统中安装Go语言的详细教程

栏    目:Golang

下一篇:Go语言实现互斥锁、随机数、time、List

本文标题:golang等待触发事件的实例

本文地址:http://www.codeinn.net/misctech/157756.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有