标签: goroutine

第一个goroutine例子,奇怪的结果

此示例取自tour.golang.org/#63

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}
Run Code Online (Sandbox Code Playgroud)

输出

hello
world
hello
world
hello
world
hello
world
hello
Run Code Online (Sandbox Code Playgroud)

为什么world只打印4时代而不是5?


编辑:答案可以引用golang规范:

程序执行从初始化主包然后调用main函数开始.当函数main返回时,程序退出.它不等待其他(非主要)goroutines完成.

go goroutine

3
推荐指数
1
解决办法
281
查看次数

等待一个例程完成的正确方法

我想知道在退出程序之前等待程序完成的正确方法是什么.阅读其他一些答案似乎bool chan会做到这一点,就像Playground链接一样

func do_stuff(done chan bool) {
    fmt.Println("Doing stuff")
    done <- true
}

func main() {
    fmt.Println("Main")
    done := make(chan bool)
    go do_stuff(done)
    <-done
    //<-done
}
Run Code Online (Sandbox Code Playgroud)

我这里有两个问题:

  • 为什么< - 完成工作?

  • 如果我取消注释最后一行会发生什么?我有一个死锁错误.这是因为频道是空的,没有其他功能向它发送值?

channel go goroutine

3
推荐指数
2
解决办法
5507
查看次数

使用两个返回参数为func创建chan

在boolInt不重新定义功能的情况下创建功能通道是否可行?

package main

func boolInt() (bool, int) {
    return false, 1
}

func main() {
    chanBool := make(chan bool)
    chanInt := make(chan int)
    go func() {
        // chanBool <- boolInt() // error: multiple-value boolInt() in single-value context
        chanBool, chanInt <- boolInt() //  syntax error: unexpected semicolon or newline, expecting := or = or comma
    }()

}
Run Code Online (Sandbox Code Playgroud)

当我尝试在单值上下文中使用它时, chanBool <- boolInt()我得到一个错误: multiple-value boolInt() in single-value context.

在2值上下文中: chanBool, chanInt <- boolInt()得到错误:syntax error: unexpected semicolon or …

channel go goroutine

3
推荐指数
1
解决办法
382
查看次数

在相同的goroutine中创建的goroutine是否始终按顺序执行?

package main

func main() {
        c:=make(chan int)
        for i:=0; i<=100;i++ {
                i:=i
                go func() {
                        c<-i
                }() 
        }   
        for {
                b:=<-c
                println(b)
                if b==100 {
                        break
                }   
        }   
}
Run Code Online (Sandbox Code Playgroud)

上面的代码创建了100个goroutine来插入num到通道c,所以我只是想知道,这些goroutines会以随机顺序执行吗?在我的测试期间,输出将始终为1到100

go goroutine

3
推荐指数
2
解决办法
489
查看次数

如何比较 Go 中通道的值

我有两个通道,首先给我一些字符串,我需要将其过滤为相同的值,然后将结果发送到第二个通道

func main() {
    c := make(chan string, 5)
    o := make(chan string, 5)
    arr := []string{"aa", "ab", "ab", "bb", "bb", "ba", "cc"}
    for _, v := range arr {
        c <- v
        go removeDuplicates(c, o)
        time.Sleep(1 * time.Second)
        fmt.Println("output: ", <-o)
    }
}

func removeDuplicates(cIn, cOut chan string) {
   last := ""
   for cur, isOpen := <-cIn; isOpen; {
      if cur != last {
        fmt.Printf("val: %s, last: %s\n", cur, last) 
        last = cur
        cOut <- cur
        //close(cOut)
      }
   } …
Run Code Online (Sandbox Code Playgroud)

concurrency channel go goroutine

3
推荐指数
1
解决办法
2472
查看次数

如果另一个 goroutine 崩溃了,如何保持 goroutine 运行?

我一直在试图找到一些东西来回答这个问题,但我找不到任何谈论它的东西。

假设我在 Go 中有一个函数,如下所示:

func main() {
    // assume this wrapped in a waitgroup or something 
    // so that it doesnt exit
    go queue.ConsumeAndDoSomething()
    go api.StartServer()
}
Run Code Online (Sandbox Code Playgroud)

我这里有两个 goroutine,它们做完全不同的事情,理想情况下,如果另一个 goroutine 崩溃/恐慌,一个应该继续运行。如果队列操作失败,API 服务器应该会受到影响,反之亦然。

我不确定这是否可能(甚至推荐)。有没有一种干净的方法可以做到这一点,或者一旦 Goroutine 发生恐慌,整个程序应该退出吗?

concurrency go goroutine

3
推荐指数
1
解决办法
3956
查看次数

golang为什么无法在主线程上向channel传值

情况1

package main

func main()  {
    dogChan := make(chan int)
    dogChan <- 1
}
Run Code Online (Sandbox Code Playgroud)
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    /Users/xuzhongwei/Source/awesomeProject/main.go:5 +0x50
Run Code Online (Sandbox Code Playgroud)

案例2

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    /Users/xuzhongwei/Source/awesomeProject/main.go:5 +0x50
Run Code Online (Sandbox Code Playgroud)
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    /Users/xuzhongwei/Source/awesomeProject/main.go:9 +0x72
Run Code Online (Sandbox Code Playgroud)

案例3

package main

func main()  {
    dogChan := make(chan int)

    go func(ch chan int) {
        
    }(dogChan)
    dogChan <- 1
} …
Run Code Online (Sandbox Code Playgroud)

go goroutine

3
推荐指数
1
解决办法
1023
查看次数

产生 goroutine 的库中出现恐慌

如果导入的库产生一个可能会出现恐慌的 goroutine 怎么办?在这种情况下,开发人员无法阻止程序退出。

就像这段代码一样,调用一个带有延迟恢复的坏库并没有帮助,因为该库正在生成一个发生恐慌的 goroutine,并且它无法被 main 的恢复捕获。

我是否理解正确的是,唯一的补救措施是在为项目选择依赖项时非常小心,并希望作者不要做类似的事情?

package main

import (
    "fmt"
    "time"
)

func main() {
    defer func() {
        r := recover()
        if r != nil {
            fmt.Println("panic caught")
        }
    }()

    badLibrary()
}

func badLibrary() {
    go recklessFunction()
    time.Sleep(time.Second)
}

func recklessFunction() {
    panic("something went wrong")
}
Run Code Online (Sandbox Code Playgroud)

go goroutine

3
推荐指数
1
解决办法
396
查看次数

是否可以取消未完成的 goroutine?

考虑一组检查工作,每个检查工作都有独立的逻辑,因此它们似乎很适合并发运行,例如:

type Work struct {
    // ...
}

// This Check could be quite time-consuming
func (w *Work) Check() bool {
    // return succeed or not

    //...
}

func CheckAll(works []*Work) {
    num := len(works)
    results := make(chan bool, num)
    for _, w := range works {
        go func(w *Work) {
            results <- w.Check()
        }(w)
    }

    for i := 0; i < num; i++ {
        if r := <-results; !r {
            ReportFailed()
            break;
        }
    }
}

func ReportFailed() {
    // …
Run Code Online (Sandbox Code Playgroud)

concurrency channel go goroutine

3
推荐指数
1
解决办法
3346
查看次数

如何使用sync/errgroup包在Go中编写并发for循环

我想同时对切片的元素执行操作
我正在使用sync/errgroup包来处理并发

这是 Go Playground 上的最小复制品https://go.dev/play/p/yBCiy8UW_80

import (
    "fmt"
    "golang.org/x/sync/errgroup"
)

func main() {
    eg := errgroup.Group{}
    input := []int{0, 1, 2}
    output1 := []int{}
    output2 := make([]int, len(input))
    for i, n := range input {
        eg.Go(func() (err error) {
            output1 = append(output1, n+1)
            output2[i] = n + 1
            return nil
        })
    }
    eg.Wait()
    fmt.Printf("with append %+v", output1)
    fmt.Println()
    fmt.Printf("with make %+v", output2)
}
Run Code Online (Sandbox Code Playgroud)

输出

with append [3 3 3]
with make [0 0 3]
Run Code Online (Sandbox Code Playgroud)

与预期相比[1 …

concurrency go slice goroutine

3
推荐指数
1
解决办法
1459
查看次数

标签 统计

go ×10

goroutine ×10

channel ×4

concurrency ×4

slice ×1