2014-09-30 44 views
0

我學習從https://talks.golang.org/2012/concurrency.slide#25「去併發模式'爲什麼頻道不工作?

問題

  1. 來自它的渠道份額可變的怎麼樣麼?在這種情況下,i已被共享。 A點和B點的變量似乎有一些特殊的關係?它是什麼 ?

  2. 這是什麼意思?

    for i:= 0; ;我+ +

主代碼:

package main 

import (
    "fmt" 
    "math/rand" 
    "time" 
) 

func boring(msg string) <-chan string { // Returns receive-only channel of strings. 

    c := make(chan string) 
    go func() { // We launch the goroutine from inside the function. 
     for i := 0; ; i++ {   // <--------- point B 
      c <- fmt.Sprintf("%s %d", msg, i) 

      time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) 
     } 
    }() 
    return c // Return the channel to the caller. 
} 

func main() { 
    c := boring("boring!") // Function returning a channel. 
    for i := 0; i < 5; i++ {    // <--------- point A 
     fmt.Printf("You say: %q\n", <-c) 
    } 
    fmt.Println("You're boring; I'm leaving.") 
} 

輸出:

You say: "boring! 0" 
You say: "boring! 1" 
You say: "boring! 2" 
You say: "boring! 3" 
You say: "boring! 4" 
You're boring; I'm leaving. 
Program exited. 
+3

你究竟如何運行它?你知道,Go不是一種腳本語言。你需要編譯程序並用'go run'運行它。另外,如果你打算運行它,它不能是'package a1',它必須是'package main' – 2014-09-30 06:38:53

+0

@Not_a_Golfer我通過更改軟件包名稱來解決問題。謝謝。但不知道它是如何工作的... – CodeFarmer 2014-09-30 07:04:25

+0

第一:通道不會導致變量或共享變量的神奇連接。實際上,渠道與變數無關。什麼渠道做的是:他們把你填入渠道的價值*放在另一端吐出相同的價值。通常這些值來自變量,並且通常這些變量具有相同(或類似)的名稱。第二:爲你提供類似於C的作品。看看這種基本問題的旅程或語言規範。 – Volker 2014-09-30 07:15:08

回答

0

for (i := 0; ; i++) { }創建索引增量永遠。

當你make(chan string)你已經創建了一個讀/寫通道。您還可以在go函數中引用通道,並將其作爲返回值傳遞出去。 Go會分析變量的使用情況,稱爲「逃逸分析」,並選擇是在堆上還是在堆棧上創建通道,以便在創建通道的函數退出時不會獲取通道釋放。