dth981485742 2017-06-20 17:08
浏览 173
已采纳

并发信号量顺序执行

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条回答 默认 最新

  • dongpin3794 2017-06-20 17:18
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。