纸箱 东莞网站建设,seo外链建设,网站建设來选宙斯站长,wordpress博客破解主题经典并发题目
现在有4个协程#xff0c;分别对应编号为1,2,3,4,每秒钟就有一个协程打印自己的编号#xff0c;要求编写一个程序#xff0c;让输出的编号总是按照1,2,3,4,1,2,3,4这样的规律一直打印下去
type Token struct {
}func newWorker(id int, ch chan Token, nextC…经典并发题目
现在有4个协程分别对应编号为1,2,3,4,每秒钟就有一个协程打印自己的编号要求编写一个程序让输出的编号总是按照1,2,3,4,1,2,3,4这样的规律一直打印下去
type Token struct {
}func newWorker(id int, ch chan Token, nextCh chan Token) {for {token : -chfmt.Println(id 1)time.Sleep(time.Second)nextCh - token}
}func testGoroutine() {chs : []chan Token{make(chan Token), make(chan Token), make(chan Token), make(chan Token)}for i : 0; i 4; i {go newWorker(i, chs[i], chs[(i1)%4])}chs[0] - struct{}{}select {}
}
信号通知题目
使用chan来实现程序的graceful shutdown在程序退出之前来执行一些连接的关闭文件的close相关操作。
func testClosed() {var closing make(chan struct{})var closed make(chan struct{})go func() {for {select {case -closing:returndefault:time.Sleep(100 * time.Millisecond)}}}()termChan : make(chan os.Signal)signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)-termChanclose(closing)go doCleanUp(closed)select {case -closed:case -time.After(time.Second):fmt.Println(clean timeout)}fmt.Println(gracefully exit)
}func doCleanUp(closed chan struct{}) {time.Sleep(time.Minute)close(closed)
}