当前位置:网站首页>Go uses channel to control concurrency

Go uses channel to control concurrency

2022-06-25 05:58:00 talen_ hx296

package main

import (
	"fmt"
	"time"
)

// Maximum number of concurrent 
const MAX_PROCESS = 10

var ch = make(chan string, MAX_PROCESS)

func main() {
	for i := 0; i < MAX_PROCESS; i++ {
		// start-up go runtine
		go recive()
	}
	time.Sleep(1 * time.Hour)
	close(ch)
}

func recive() {
	for data := range ch {
		DoSomething(data)
	}
}

func DoSomething(data string) error {
	defer dopanic()
	fmt.Sprintf("doing %s...", data)
	return nil
}

func dopanic() {
	if r := recover(); r != nil {
		fmt.Errorf("Error: %+v", r)
	}
}

原网站

版权声明
本文为[talen_ hx296]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202201251156736.html