go并发操作且限制数量

  • 使用管道chan

func returnNum() int64 {
	return time.Now().Unix()
}
func main() {
	threadAmount := runtime.GOMAXPROCS(0)
	if threadAmount < 2 {
		threadAmount = 2
	}
	fmt.Println(threadAmount)
	threadChan := make(chan int, threadAmount)
	defer close(threadChan)
	for {
		for i := 1; i <= threadAmount; i++ {
			threadChan <- i
			go func(threadChan chan int) {
				defer func() {
					<-threadChan
				}()
				fmt.Println(returnNum())
				fmt.Println("########")
			}(threadChan)
		}
		fmt.Println("Goroutine count:", runtime.NumGoroutine())
	}
}
  • 使用线程组sync.WaitGroup

将在一组任务都结束后再开始新的一轮

func main() {
	var wg sync.WaitGroup
	threadNum := 5
	count := 0
	for {
		count++
		logger.Debug("一轮开始:%d", count)
		jobs := make(chan int, threadNum)
		for i := 0; i < threadNum; i++ {
			wg.Add(1)
			go func(thread int, jobs <-chan int, wg *sync.WaitGroup) {
				defer wg.Done()
				for item := range jobs {
					fmt.Println("线程:", thread, "#####", item)
				}
			}(i, jobs, &wg)
		}
		for i := 0; i < threadNum; i++ {
			jobs <- i
		}
		close(jobs)
		wg.Wait()
		logger.Debug("一轮结束:%d", count)
	}
}

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