英文:
Concurrency semaphore sequential execution
问题
如何使用信号量在并发中按顺序执行 Go 程序?
我有一个简单的程序,它只是打印从包含数字的数组中读取的内容。
package main
import "fmt"
import "sync"
type empty struct{}
type semaphore chan empty
// 获取 n 个资源
func (sem semaphore) P(n int) {
e := empty{}
for i := 0; i < n; i++ {
sem <- e
}
}
// 释放 n 个资源
func (sem semaphore) V(n int) {
for i := 0; i < n; i++ {
<-sem
}
}
func main() {
var wg sync.WaitGroup
sm := make(semaphore, 2)
var arr []int = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
for _, val := range arr {
wg.Add(1)
go func(val int) {
sm.P(1)
defer sm.V(1)
defer wg.Done()
fmt.Print(" val:", val)
}(val)
}
wg.Wait()
}
输出:
9 1 2 3 4 5 6 7 8
但我希望输出按照数组声明的顺序:
1 2 3 4 5 6 7 8 9
英文:
How can I execute a Go program in concurrency using semaphore sequentially?
I have a small program which just prints reading from an array which contain numbers
package main
import "fmt"
import "sync"
type empty struct{}
type semaphore chan empty
// acquire n resources
func (sem semaphore) P(n int) {
e := empty{}
for i := 0; i < n; i++ {
sem <- e
}
}
// release n resources
func (sem semaphore) V(n int) {
for i := 0; i < n; i++ {
<-sem
}
}
func main() {
var wg sync.WaitGroup
sm := make(semaphore, 2)
var arr []int = []int{1,2,3,4,5,6,7,8,9}
for _,val := range arr{
wg.Add(1)
go func(val int){
sm.P(1)
defer sm.V(1)
defer wg.Done()
fmt.Print(" val:",val)
}(val)
}
wg.Wait()
}
Output:
9 1 2 3 4 5 6 7 8
But I want the output to be like this (as per the array declaration)
1 2 3 4 5 6 7 8 9
答案1
得分: 2
一个信号量或互斥锁用于控制同步,而不是操作的顺序。无论操作是否同步,同时进行的操作的顺序是不可控制或可预测的。如果你需要控制操作的顺序,就不应该同时执行这些操作。
英文:
A semaphore or mutex controls synchronization, not order of operations. The order of concurrent operations, regardless of whether or not they're synchronized, is not controllable or predictable. If you need a controlled order of operations, you should not execute those operations concurrently.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论