当我试图打印出来时:
fmt.Println(c <- x)在下面的代码块中的for循环之前,看看"c < - x"将评估什么,它得到了错误消息:
./select.go:7:发送语句c < - x用作值; 使用select进行非阻塞发送
如果发送操作成功,"c < - x"是否被评估为真?为什么Go只允许你在select语句中的case语句中使用send语句的值(也就是"c < - x"的值)?
func fibonacci(c, quit chan int) {
x, y := 1, 1
for {
select {
case c <- x:
x, y = y, x + y
case <-quit:
fmt.Println("quit")
return
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
显然,我的代码中存在竞争条件.但我无法找到它,因为我很确定要正确同步.经过几个小时的调试,你可能会帮我找到它.
首先,这是我的(非常简化的)代码:
package main
import (
"log"
"time"
)
type Parser struct {
callback Callback
callbackSet chan bool
test int
}
func NewParser() Parser {
p := Parser{}
p.test = 100
p.callbackSet = make(chan bool)
return p
}
func (p *Parser) SetCallback(newCallback Callback) {
log.Println("=> SET CALLBACK: ", newCallback)
p.test = 100
p.callback = newCallback
log.Println("=> SETTING CALLBACK DONE")
p.callbackSet <- true
}
func (p *Parser) StartParsing() {
go p.parse()
}
func (p *Parser) parse() {
cb := <-p.callbackSet
_ …Run Code Online (Sandbox Code Playgroud) 此递归函数按预期工作(返回5行,数字5到1):
package main
import (
"fmt"
)
func recur(iter int) {
if iter <= 0 {
return
}
fmt.Println(iter)
recur(iter-1)
}
func main() {
recur(5)
}
Run Code Online (Sandbox Code Playgroud)
这个没有(只返回1行5号):
package main
import (
"fmt"
)
func recur(iter int) {
if iter <= 0 {
return
}
fmt.Println(iter)
go recur(iter-1)
}
func main() {
recur(5)
}
Run Code Online (Sandbox Code Playgroud)
不同之处在于,在第二个实现中,函数将自身称为goroutine.(线go recur(iter-1))
有人可以解释这种行为吗?
盯着运行递归函数的goroutine,我想发送一个信号来阻止那些递归函数.这是功能(功能并不重要):
func RecursiveFunc(x int, depth int, quit chan bool) int {
if depth == 0 {
return 1
}
if quit != nil {
select {
case <-quit:
return 0
default:
}
}
total := 0
for i := 0; i < x; i++ {
y := RecursiveFunc(x, depth - 1, quit)
if y > 0 {
total += y
}
}
return total
}
Run Code Online (Sandbox Code Playgroud)
此功能可能需要很长时间才能完成,我想在发送退出信号并使用结果(无论是什么)后停止它.要运行它:
import (
"fmt"
"time"
"sync"
)
func main() {
quit := make(chan bool)
wg …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用通道来实现一种工作池。请看下面的代码
https://play.golang.org/p/g7aKxDoP9lf(围棋游乐场)
package main
import (
"fmt"
"time"
)
func main() {
q1 := make(chan int)
fmt.Printf("worker 1\n")
go worker1(q1)
for i := 0; i < 10; i++ {
fmt.Printf("sending: %v\n", i)
q1 <- i
}
time.Sleep(time.Second)
fmt.Printf("\n\nworker 2\n")
q2 := make(chan *int)
go worker2(q2)
for i := 0; i < 10; i++ {
fmt.Printf("sending: %v\n", i)
q2 <- &i
}
time.Sleep(time.Second)
}
func worker1(qTodo <-chan int) {
var curr int
for {
select {
case curr = <-qTodo: …Run Code Online (Sandbox Code Playgroud) 对于下面的代码段,当收到^ C时,不会进行延迟呼叫.清理是否可能引入竞争条件?如果是,那么在接收中断时可能有更好的清理模式?
func fn() {
// some code
defer cleanup()
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
// Block until a signal is received.
_ = <-c
cleanup()
}
for {
// Infinite loop. Returns iff an error is encountered in the
// body
}
}
Run Code Online (Sandbox Code Playgroud) 我想在超时时停止执行goroutine.但似乎它对我不起作用.我正在使用iris框架.
type Response struct {
data interface{}
status bool
}
func (s *CicService) Find() (interface{}, bool) {
ch := make(chan Response, 1)
go func() {
time.Sleep(10 * time.Second)
fmt.Println("test")
fmt.Println("test1")
ch <- Response{data: "data", status: true}
}()
select {
case <-ch:
fmt.Println("Read from ch")
res := <-ch
return res.data, res.status
case <-time.After(50 * time.Millisecond):
return "Timed out", false
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Timed out
test
test1
Run Code Online (Sandbox Code Playgroud)
预期产出:
Timed out
Run Code Online (Sandbox Code Playgroud)
有人能指出这里缺少什么吗?它确实超时但仍然运行goroutine打印test和test1.我只想在超时后立即停止执行goroutine.
如何创建包含原始文件中存储的所有值的Go上下文的副本(如果愿意,则为克隆),但在原始文件中不会被取消?
它似乎对我来说是一个有效的用例.假设我有一个http请求,并且在将响应返回给客户端后取消其上下文,并且我需要在单独的goroutine中在此请求的末尾运行异步任务,该任务很可能比父上下文更长.
func Handler(ctx context.Context) (interface{}, error) {
result := doStuff(ctx)
newContext := howDoICloneYou(ctx)
go func() {
doSomethingElse(newContext)
}()
return result
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以建议如何做到这一点?
当然,我可以跟踪可能放入上下文的所有值,创建一个新的后台ctx,然后只是迭代每个可能的值并复制......但这似乎很乏味,很难在大型代码库中进行管理.
我的代码如下:
package main
import (
"fmt"
)
func main() {
c1 := make(chan int)
fmt.Println("push c1: ")
c1 <- 10
g1 := <- c1
fmt.Println("get g1: ", g1)
}
Run Code Online (Sandbox Code Playgroud)
当我使用 delve 进行调试时,它会打印以下结果:
push c1:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
D:/Go/projects/hello-world/src/ch9/code9_6/code1.go:10 +0xde
Process 6276 has exited with status 2
Run Code Online (Sandbox Code Playgroud)
我不知道为什么,这只是一个简单的渠道示例,我创建了一个渠道,向其发送价值并从中获取价值,仅此而已,有人可以告诉我为什么,以及如何纠正它,非常感谢。
我正在编写一个调用其他微服务的微服务,用于很少更新的数据(一天一次或一个月一次)。所以我决定创建缓存,并实现了这个接口:
type StringCache interface {
Get(string) (string, bool)
Put(string, string)
}
Run Code Online (Sandbox Code Playgroud)
在内部,它只是map[string]cacheItem,在哪里
type cacheItem struct {
data string
expire_at time.Time
}
Run Code Online (Sandbox Code Playgroud)
我的同事说它不安全,我需要在我的方法中添加互斥锁,因为它将被 http 处理程序函数的不同实例并行使用。我有一个测试,但它没有检测到数据竞争,因为它在一个 goroutine 中使用缓存:
func TestStringCache(t *testing.T) {
testDuration := time.Millisecond * 10
cache := NewStringCache(testDuration / 2)
cache.Put("here", "this")
// Value put in cache should be in cache
res, ok := cache.Get("here")
assert.Equal(t, res, "this")
assert.True(t, ok)
// Values put in cache will eventually expire
time.Sleep(testDuration)
res, ok = cache.Get("here")
assert.Equal(t, res, "")
assert.False(t, ok) …Run Code Online (Sandbox Code Playgroud) go ×10
goroutine ×10
channel ×2
asynchronous ×1
cancellation ×1
channels ×1
go-iris ×1
pointers ×1
recursion ×1