zoukankan      html  css  js  c++  java
  • golang的channel 这个行为很奇怪

    有点奇怪,记录一下:

    下面这个图执行了3个

     package main
     
     import (
       "fmt"
     )
     
     func main() {
       c := make(chan string)
     
       for i := 0; i < 5; i++ {
         go func(i int) {
           msg := <- c
           c <- fmt.Sprintf("%s, hi from %d", msg, i)
         }(i)
       }
     
       c <- "original"
     
       fmt.Println(<-c)
     }
    

      

    --------------------------------------

    // This sample program demonstrates how to use an unbuffered
    // channel to simulate a game of tennis between two goroutines.
    package main
    
    import (
    	"fmt"
    	"math/rand"
    	"sync"
    	"time"
    )
    
    // wg is used to wait for the program to finish.
    var wg sync.WaitGroup
    
    func init() {
    	rand.Seed(time.Now().UnixNano())
    }
    
    // main is the entry point for all Go programs.
    func main() {
    	// Create an unbuffered channel.
    	court := make(chan int)
    
    	// Add a count of two, one for each goroutine.
    	wg.Add(2)
    
    	// Launch two players.
    	go player("Nadal", court)
    	go player("Djokovic", court)
    
    	// Start the set.
    	court <- 1
    
    	// Wait for the game to finish.
    	wg.Wait()
    }
    
    // player simulates a person playing the game of tennis.
    func player(name string, court chan int) {
    	// Schedule the call to Done to tell main we are done.
    	defer wg.Done()
    
    	for {
    		// Wait for the ball to be hit back to us.
    		ball, ok := <-court
    		if !ok {
    			// If the channel was closed we won.
    			fmt.Printf("Player %s Won
    ", name)
    			return
    		}
    
    		// Pick a random number and see if we miss the ball.
    		n := rand.Intn(100)
    		if n%13 == 0 {
    			fmt.Printf("Player %s Missed
    ", name)
    
    			// Close the channel to signal we lost.
    			close(court)
    			return
    		}
    
    		// Display and then increment the hit count by one.
    		fmt.Printf("Player %s Hit %d
    ", name, ball)
    		ball++
    
    		// Hit the ball back to the opposing player.
    		court <- ball
    	}
    }
    

      

  • 相关阅读:
    单例模式(Singleton)
    cdlinux
    android 去锯齿
    ide
    图片加载内存溢出
    android AlertDialog 弹出窗
    找回 文件下载 ie 窗口
    javac 多个jar文件 用封号 隔开
    android 模拟按钮点击
    android 加载多个图片 内在溢出的问题
  • 原文地址:https://www.cnblogs.com/oxspirt/p/13631927.html
Copyright © 2011-2022 走看看