您的位置 首页 golang

猫狗鱼Go协程顺序并发经典实例

随笔记录,测试了一下经典的猫狗鱼Go协程并发经典实例,间隔一秒并发输出cat
dog fish 以及输出100次的代码,本实例考察,sync.WaitGroup的用法,以及协程按指定的顺序执行。

 package main

func main(){
	var wg sync.WaitGroup

	catChan := make(chan struct{})
	dogChan := make(chan struct{})
	fishChan := make(chan struct{})

	cat(&wg, catChan, fishChan)
	dog(&wg, dogChan, catChan)
	fish(&wg, fishChan, dogChan)

	wg.Wait()

}

func cat(wg *sync.WaitGroup, catChan, fishChan chan struct{}) {
	wg.Add(1)
	go func() {
		for {
			fmt.Println("cat")
			catChan <- struct{}{}
			<-fishChan
		}
		wg.Done()
	}()

}

func dog(wg *sync.WaitGroup, dogChan, catChan chan struct{}) {
	wg.Add(1)
	go func() {
		for {
			<-catChan
			fmt.Println("dog")
			dogChan <- struct{}{}
		}
		wg.Done()
	}()

}

func fish(wg *sync.WaitGroup, fishChan, dogChan chan struct{}) {

	wg.Add(1)
	go func() {
		for {
			<-dogChan
			fmt.Println("fish")
			time.Sleep(1 * time.Second)
			fishChan <- struct{}{}

		}
		wg.Done()
	}()

}

  

// 打印100次

 
func cat(wg *sync.WaitGroup, catChan, fishChan chan struct{}) {
	wg.Add(1)
	go func() {
		var counter int64
		for counter <= 100 {
			atomic.AddInt64(&counter, 1)
			fmt.Println("cat")
			catChan <- struct{}{}
			<-fishChan
		}
		wg.Done()
	}()

}

func dog(wg *sync.WaitGroup, dogChan, catChan chan struct{}) {
	wg.Add(1)
	go func() {
		var counter int64
		for counter <= 100 {
			atomic.AddInt64(&counter, 1)
			<-catChan
			fmt.Println("dog")
			dogChan <- struct{}{}
		}
		wg.Done()
	}()

}

func fish(wg *sync.WaitGroup, fishChan, dogChan chan struct{}) {
	wg.Add(1)
	go func() {
		var counter int64
		for counter <= 100 {
			atomic.AddInt64(&counter, 1)
			<-dogChan
			fmt.Println("fish")
			fishChan <- struct{}{}

		}
		wg.Done()
	}()

}  

文章来源:智云一二三科技

文章标题:猫狗鱼Go协程顺序并发经典实例

文章地址:https://www.zhihuclub.com/86296.shtml

关于作者: 智云科技

热门文章

发表评论

您的电子邮箱地址不会被公开。

网站地图