Go的并发练习题目

经典并发题目

现在有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 := <-ch
		fmt.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[(i+1)%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:
				return
			default:
				time.Sleep(100 * time.Millisecond)
			}
		}
	}()

	termChan := make(chan os.Signal)
	signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
	<-termChan

	close(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)
}

你可能感兴趣的:(golang,golang,后端,开发语言)