3 回答

TA貢獻(xiàn)1839條經(jīng)驗 獲得超15個贊
我想覆蓋它們,因此我需要事先關(guān)閉頻道
不,不需要關(guān)閉頻道。當(dāng)另一個項目通過通道推送時,它將恢復(fù)迭代。
下面的代碼接受控制臺輸入并將其推送到頻道:
主程序
package main
import (
"log"
"bufio"
"os"
"fmt"
)
func process(c chan string) {
for s := range c {
log.Println("processed", s)
}
}
func main() {
c := make(chan string, 10)
go process(c)
// get from console and process
reader := bufio.NewReader(os.Stdin)
fmt.Println("INPUT STUFF. TYPE #quit TO EXIT.")
for {
input, _, _ := reader.ReadLine()
if string(input) == "#quit" {
break
}
c <- string(input)
}
log.Println("BYE!")
}
輸出
INPUT STUFF. TYPE #quit TO EXIT.
hello
2018/10/23 10:43:52 processed hello
world
2018/10/23 10:43:54 processed world
#quit
2018/10/23 10:43:57 BYE!
下面的示例使用并可作為 Go Playground片段Sleep()運行
package main
import (
"log"
"time"
)
func process(c chan string) {
for s := range c {
log.Println("processed", s)
}
}
func main() {
c := make(chan string, 10)
go process(c)
// push some data
c <- "barry allen"
c <- "iris west"
time.Sleep(time.Second * 2)
// push more data
c <- "joe west"
c <- "caitlin snow"
time.Sleep(time.Second * 3)
}
輸出
2009/11/10 23:00:00 processed barry allen
2009/11/10 23:00:00 processed iris west
2009/11/10 23:00:02 processed joe west
2009/11/10 23:00:02 processed caitlin snow
希望這可以幫助。干杯,

TA貢獻(xiàn)1810條經(jīng)驗 獲得超4個贊
您不能重新打開已關(guān)閉的頻道,但可以channel
在頻道上發(fā)送,也許這就是您要找的?
package main
import (
? ? "fmt"
? ? "time"
)
func main() {
? ? queue := make(chan chan int)
? ? defer close(queue)
? ? go func() { // reader
? ? ? ? for {
? ? ? ? ? ? ch := <-queue
? ? ? ? ? ? for i := range ch {
? ? ? ? ? ? ? ? fmt.Println(i)
? ? ? ? ? ? }
? ? ? ? ? ? fmt.Println("Done with this channel")
? ? ? ? }
? ? }()
? ? go func() { // writer-1
? ? ? ? ch := make(chan int)
? ? ? ? defer close(ch)
? ? ? ? queue <- ch
? ? ? ? ch <- 4
? ? ? ? ch <- 2
? ? }()
? ? go func() { // writer-2
? ? ? ? ch := make(chan int)
? ? ? ? defer close(ch)
? ? ? ? queue <- ch
? ? ? ? ch <- 4
? ? ? ? ch <- 20
? ? }()
? ? time.Sleep(time.Second)
}

TA貢獻(xiàn)1780條經(jīng)驗 獲得超5個贊
雖然您無法重新打開頻道,但可以創(chuàng)建一個新頻道并分配給變量。先前關(guān)閉的通道將被垃圾收集。在本例中,我重用了該queue變量,但您也可以創(chuàng)建一個新queue2變量并將其傳遞給 goroutine。
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
queue := make(chan int)
go printFormat(nil, queue)
queue <- 1
queue <- 2
close(queue)
// fake some actions in between
time.Sleep(2 * time.Second)
queue = make(chan int)
go printFormat(cancel, queue)
queue <- 3
queue <- 4
close(queue)
<-ctx.Done()
}
func printFormat(c context.CancelFunc, q chan int) {
for i := range q {
fmt.Printf("Data %d \n", i)
}
if c != nil {
c()
}
}
- 3 回答
- 0 關(guān)注
- 147 瀏覽
添加回答
舉報