gpt4 book ai didi

go - 如何使用<-chan 和chan<- 进行单向通信?

转载 作者:IT王子 更新时间:2023-10-29 01:33:44 26 4
gpt4 key购买 nike

我正在努力了解 Go 的 channel 。我想我了解基本的双向 chan但我不了解 <-chanchan<- .

我希望它们能以一种方式与线程通信,但我在线程实际读取和接收值时遇到了问题。

package main

import (
"fmt"
"time"
)

func Thread(c chan<- int) {
for {
num := <-c
fmt.Println("Thread : ", num)
time.Sleep(time.Second)
}
}

func main() {
c := make(chan<- int, 3)
go Thread(c)
for i := 1; i <= 10; i++ {
c <- i
}
for len(c) > 0 {
time.Sleep(100)
}
}

我试过使用 <-chan而不是 chan<-make()但同样的事情发生了:

C:\>go run chan.go
# command-line-arguments
.\chan.go:10: invalid operation: <-c (receive from send-only type chan<- int)

如果我不能从 channel 读取,为什么还要写呢?考虑到这个想法,我想我一定做错了什么。我期望只发送 chan这意味着一个线程只能发送而另一个线程只能接收。似乎并非如此。

如果我删除 <-完全,它有效,但这会使它成为双向的,允许 go 例程响应(即使它从不响应),我希望避免这种情况。好像我可以把数字放逐到 chan我永远无法读取,或者我可以从 chan 读取这是不可能写的。

我希望做的是将整数从主线程发送到 go 例程,以便它使用单向 channel 进行打印。我做错了什么?

如果重要的话,这是 Windows 上的 go 1.3.3。更新到 1.4 没有帮助。我可能想提一下这也是所有 x64。

最佳答案

The Go Programming Language Specification

Channel types

A channel provides a mechanism for concurrently executing functions to communicate by sending and receiving values of a specified element type. The value of an uninitialized channel is nil.

ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType .

The optional <- operator specifies the channel direction, send or receive. If no direction is given, the channel is bidirectional. A channel may be constrained only to send or only to receive by conversion or assignment.

您可以通过转换或赋值明确 channel 方向。例如,通过转换,

package main

import (
"fmt"
"time"
)

func Thread(r <-chan int) {
for {
num := <-r
fmt.Println("Thread : ", num)
time.Sleep(time.Second)
}
}

func main() {
c := make(chan int, 3)
s, r := (chan<- int)(c), (<-chan int)(c)
go Thread(r)
for i := 1; i <= 10; i++ {
s <- i
}
for len(c) > 0 {
time.Sleep(100)
}
}

输出:

Thread :  1Thread :  2Thread :  3. . .

Or, equivalently, by assignment,

package main

import (
"fmt"
"time"
)

func Thread(r <-chan int) {
for {
num := <-r
fmt.Println("Thread : ", num)
time.Sleep(time.Second)
}
}

func main() {
c := make(chan int, 3)
var s chan<- int = c
var r <-chan int = c
go Thread(r)
for i := 1; i <= 10; i++ {
s <- i
}
for len(c) > 0 {
time.Sleep(100)
}
}

关于go - 如何使用<-chan 和chan<- 进行单向通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com