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 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效