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.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?