英文:
Go use channel to alternated print
问题
我想让我的代码打印出:
12AB34CD56EF78GH910IJ
但实际上它打印出:
12AB3456CDEF78910GHIJ
我很困惑,觉得这很奇怪。
package main
import (
"fmt"
"sync"
)
func main() {
numdone := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
data := []byte("ABCDEFGHIJ")
for i := 0; i < 10; i = i + 2 {
<-numdone
fmt.Printf("%c", data[i])
fmt.Printf("%c", data[i+1])
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 1; i < 11; i = i + 2 {
fmt.Printf("%d", i)
fmt.Printf("%d", i+1)
numdone <- i
}
}()
wg.Wait()
}
英文:
I want my code to print:
12AB34CD56EF78GH910IJ
but it prints:
12AB3456CDEF78910GHIJ
I am so confused and I think it is strange.
package main
import (
"fmt"
"sync"
)
func main() {
numdone := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
data := []byte("ABCDEFGHIJ")
for i := 0; i < 10; i = i + 2 {
<-numdone
fmt.Printf("%c", data[i])
fmt.Printf("%c", data[i+1])
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 1; i < 11; i = i + 2 {
fmt.Printf("%d", i)
fmt.Printf("%d", i+1)
numdone <- i
}
}()
wg.Wait()
}
答案1
得分: 1
请阅读我上面的评论。要进行同步,只需使用互斥锁即可:
package main
import (
"fmt"
"sync"
)
var mu sync.Mutex
func main() {
numdone := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
data := []byte("ABCDEFGHIJ")
for i := 0; i < 10; i = i + 2 {
<-numdone
fmt.Printf("%c", data[i])
fmt.Printf("%c", data[i+1])
mu.Unlock()
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 1; i < 11; i = i + 2 {
mu.Lock()
fmt.Printf("%d", i)
fmt.Printf("%d", i+1)
numdone <- i
}
}()
wg.Wait()
}
Playground: https://play.golang.org/p/71Dv0iKTy_
英文:
Please read my comment above. To synchronize, just use a mutex and it'll work:
package main
import (
"fmt"
"sync"
)
var mu sync.Mutex
func main() {
numdone := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
data := []byte("ABCDEFGHIJ")
for i := 0; i < 10; i = i + 2 {
<-numdone
fmt.Printf("%c", data[i])
fmt.Printf("%c", data[i+1])
mu.Unlock()
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 1; i < 11; i = i + 2 {
mu.Lock()
fmt.Printf("%d", i)
fmt.Printf("%d", i+1)
numdone <- i
}
}()
wg.Wait()
}
Playground : https://play.golang.org/p/71Dv0iKTy_
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论