golang中使用多线程和channel通道

package controller

import (
	"context"
	"github.com/gogf/gf/v2/os/grpool"
	"sync"
	"testing"
	"time"
)

func TestChan(t *testing.T) {
	// 创建channel通道
	testChan:= make(chan int,100)
	// 创建线程池
	pool := grpool.New(10)
	// 创建等待组
	wg := sync.WaitGroup{}
	for i := 0; i < 3; i++ {
		// 等待组 +1
		wg.Add(1)
		sonI:=i
		// 从线程池中开启一个线程跑任务
		pool.Add(context.Background(), func(ctx context.Context) {
			if 1==1 {
				testChan <- sonI
				time.Sleep(1000)
			}
			// 线程执行完毕后 等待组 -1
			defer wg.Done()
		})
	}
	// 等待所有线程执行完毕
	wg.Wait()
	// 关闭channel
	close(testChan)
	list:= make([]int,0)
	// 使用for循环读取channel中的数据
	for  {
		val, ok := <-testChan
		if !ok {
			break
		}
		list = append(list,val)
	}

	t.Log(list)
}

posted @ 2022-08-22 11:36  挎木剑的游侠儿  阅读(242)  评论(0编辑  收藏  举报