Go简单的方法来创建多线程 (multi-gopher) 程序

下面展示一些 示例代码

Goroutines
func main(){
	theMine := [5]string{"rock", "ore", "ore", "rock", "ore"}
	go findOre(theMine)
	go findOre2(theMine)
	<-time.After(time.Second * 5)
}
func findOre(s [5]string){
	for _,v := range s{
		fmt.Println("ore1",v)
	}
}
func findOre2(s [5]string){
	for _,v1 := range s{
		fmt.Println("ore2",v1)
	}
}
Channels
func main() {
	theMine := [5]string{"ore1", "ore2", "ore3"}
	oreChan := make(chan string)


	// Finder
	go func(mine [5]string) {
		for _, item := range mine {
			oreChan <- item //send
		}

	}(theMine)
	fmt.Println(oreChan)
	// Ore Breaker
	go func() {
		for i := 0; i < 3; i++ {
			foundOre := <-oreChan //receive
			fmt.Println("Miner: Received " + foundOre + " from finder")
		}
	}()
	<-time.After(time.Second * 1)
}

Unbuffered Channels
func main() {
	bufferedChan := make(chan string, 4)

	go func() {
		bufferedChan <-"first"
		fmt.Println("Sent 1st")
		bufferedChan <-"second"
		fmt.Println("Sent 2nd")
		bufferedChan <-"third"
		fmt.Println("Sent 3rd")
	}()

	<-time.After(time.Second * 1)

	go func() {
		firstRead := <- bufferedChan
		fmt.Println("Receiving..")
		fmt.Println(firstRead)
		secondRead := <- bufferedChan
		fmt.Println(secondRead)
		thirdRead := <- bufferedChan
		fmt.Println(thirdRead)
	}()
	<-time.After(time.Second * 1)
}
goroutines 和 channels 
func main() {
	theMine := [5]string{"rock", "ore", "ore", "rock", "ore"}
	oreChannel := make(chan string)
	minedOreChan := make(chan string)

	// Finder
	go func(mine [5]string) {
		for k, item := range mine {
			if item == "ore" {
				fmt.Println("ore position:", k)
				oreChannel <- item //send item on oreChannel
			}
		}
	}(theMine)

	// Ore Breaker
	go func() {
		for i := 0; i < 3; i++ {
			foundOre := <-oreChannel //read from oreChannel
			fmt.Println("From Finder:", foundOre)
			minedOreChan <-"minedOre" //send to minedOreChan
		}
	}()

	// Smelter
	go func() {
		for i := 0; i < 3; i++ {
			minedOre := <-minedOreChan //read from minedOreChan
			fmt.Println("From Miner:", minedOre)
			fmt.Println("From Smelter: Ore is smelted")
		}
	}()

	<-time.After(time.Second * 3) // Again, you can ignore this
}
发布了2 篇原创文章 · 获赞 0 · 访问量 299

猜你喜欢

转载自blog.csdn.net/weixin_43844941/article/details/105359090