channel的关闭和广播

代码主要测试 golang中 channel的生产者和接受者的使用方式


Demo1:

package ch8

import (
	"fmt"
	"sync"
	"testing"
)

func Producer(ch chan int, wg *sync.WaitGroup) {
	//生产者
	go func() {
		for i := 0; i < 50; i++ {
			ch <- i
		}
		close(ch)
		wg.Done()
	}()
}

func Consumer(ch chan int, wg *sync.WaitGroup) {
	//消费者
	go func() {
		for {
			if data, ok := <-ch; ok {
				fmt.Println(data)
			} else {
				break
			}
		}
		wg.Done()
	}()
}

func TestChannel(t *testing.T) {
	var wg sync.WaitGroup
	ch := make(chan int, 1)
	wg.Add(1)
	Producer(ch, &wg)
	wg.Add(1)
	Consumer(ch, &wg)
	wg.Add(1)
	Consumer(ch, &wg)
	wg.Add(1)
	Consumer(ch, &wg)

	wg.Wait()
}



Demo2:



package gy_close

import (
	"fmt"
	"testing"
	"time"
)

func isCancelled(cancelChan chan struct{}) bool {
	select {
	case <-cancelChan:
		return true
	default:
		return false
	}
}

func cancel_1(cancelChan chan struct{}) {
	cancelChan <- struct{}{}
}

func cancel_2(cancelChan chan struct{}) {
	close(cancelChan)
}

func TestCancel(t *testing.T) {
	cancelChan := make(chan struct{}, 0)
	for i := 0; i < 5; i++ {
		go func(i int, cancelCh chan struct{}) {
			for {
				if isCancelled(cancelCh) {
					break
				}
				time.Sleep(time.Millisecond * 5)
			}
			fmt.Println(i, "Cancelled")
		}(i, cancelChan)
	}
	cancel_2(cancelChan)
	time.Sleep(time.Second * 1)
}



原文链接: channel的关闭和广播 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-557.html )

发表评论

0则评论给“channel的关闭和广播”