我有两个 go 例程:
func f1 {
... some code
// critical section 1 (CS1)
... critical section code
// end criticla section 1
... more code
}
func f2 {
... some code
// critical section 2 (CS2)
... critical section code
// end criticla section 2
... more code
}
func main() {
go f1()
go f2()
}
Run Code Online (Sandbox Code Playgroud)
确保这些例程中的关键部分始终交替执行的正确方法是什么?
换句话说,CS1 只能在 CS2 之后执行,反之亦然:CS1、CS2、CS1、CS2、CS1 等。
我尝试用 Go 编写一个程序,在非常大的 DNA 序列文件中查找一些基因。我已经编写了一个 Perl 程序来执行此操作,但我想利用 goroutine 并行执行此搜索;)
因为文件很大,所以我的想法是一次读取 100 个序列,然后将分析发送到 goroutine,然后再次读取 100 个序列,依此类推。
我要感谢这个网站的成员对于切片和 goroutine 的非常有用的解释。
我已经进行了建议的更改,以使用 goroutine 处理的切片的副本。但 -race 执行仍然在函数级别检测到一个数据竞争copy():
非常感谢您的评论!
==================
WARNING: DATA RACE
Read by goroutine 6:
runtime.slicecopy()
/usr/lib/go-1.6/src/runtime/slice.go:113 +0x0
main.main.func1()
test_chan006.go:71 +0xd8
Previous write by main goroutine:
main.main()
test_chan006.go:63 +0x3b7
Goroutine 6 (running) created at:
main.main()
test_chan006.go:73 +0x4c9
==================
[>5HSAA098909 BA098909 ...]
Found 1 data race(s)
exit status 66
line 71 is : copy(bufCopy, buf_Seq)
line 63 is : buf_Seq = append(buf_Seq, …Run Code Online (Sandbox Code Playgroud) 我有一个频道,接收器是主要的。我生成多个 goroutine,每个 goroutine 通过通道发送一个字符串。
现在,这会导致死锁,因为我没有使用 close 函数正确关闭通道。问题是,我不知道将创建多少个 goroutine,因此无法知道何时关闭通道。
我尝试过使用 WaitGroup,问题是,我读到我不能在 goroutine 中使用 Add,我应该在主进程/goroutine 中使用 wg.Add(1),我尝试过使用 Add in父 Goroutine 生成子 Goroutine,这也导致了死锁
包主
import (
"fmt"
"sync"
)
var i = 0
func doSomething(ch chan string, wg sync.WaitGroup) {
defer wg.Done()
ch <- fmt.Sprintf("doSomething: %d", i)
i++
if i == 10 {return}
wg.Add(1)
go doSomething(ch, wg)
}
func main() {
ch := make(chan string)
var wg sync.WaitGroup
wg.Add(1)
go doSomething(ch, wg)
wg.Wait()
for s := range ch {
fmt.Println(s)
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这只是一个测试代码,所以,假设我们不知道我们只会创建 …
我是新手,尝试让两种方法在应用程序运行时定期同时运行。我已经设法想出以下内容,但该for true部分感觉不正确,因为这是阻塞的。
渠道是实现这一目标的更好方法吗?任何指向正确方向的指针都会有所帮助。
func main() {
t1 := schedule(ping, time.Second)
t2 := schedule(ping, 2*time.Second)
for true {
time.Sleep(1 * time.Second)
}
t1.Stop()
t2.Stop()
}
func schedule(f func(interval time.Duration), interval time.Duration) *time.Ticker {
ticker := time.NewTicker(interval)
go func() {
for range ticker.C {
f(interval)
}
}()
return ticker
}
func ping(interval time.Duration) {
log.Println("ping ", interval)
}
Run Code Online (Sandbox Code Playgroud) 比如说,我有一个函数,func foo(x) error { if x == y ... return err}我想在多个 go 例程中执行并聚合错误(最好使用错误组,如下面的常见示例),但不确定这是否可能?
import "golang.org/x/sync/errgroup"
var g errgroup.Group
g.Go(func() error {
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
}
return err
})
Run Code Online (Sandbox Code Playgroud) 我正在调试一个通过 Goland 用 go 编写的程序。在调试器中,我可以在正在运行的不同 goroutine 之间进行选择。我发现在我的 goroutine 旁边还有很多其他名为 runtime.gopark 的 goroutine,我怀疑这些是在线程池中等待工作的其他线程。但是,我在网上找不到任何答案。是这样吗?如果不是,它实际上在做什么?
PS这是事件的照片:
我有两个通道,首先给我一些字符串,我需要将其过滤为相同的值,然后将结果发送到第二个通道
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) 我一直在试图找到一些东西来回答这个问题,但我找不到任何谈论它的东西。
假设我在 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 发生恐慌,整个程序应该退出吗?
情况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) 如果导入的库产生一个可能会出现恐慌的 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)