并发信号量顺序执行

huangapple go评论64阅读模式
英文:

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 &quot;fmt&quot;
import &quot;sync&quot;

type empty struct{}

 type semaphore chan empty

 // acquire n resources
 func (sem semaphore) P(n int) {
 e := empty{}
 for i := 0; i &lt; n; i++ {
	sem &lt;- e
 }
 }
 // release n resources
 func (sem semaphore) V(n int) {
    for i := 0; i &lt; n; i++ {
	    &lt;-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(&quot; val:&quot;,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.

huangapple
  • 本文由 发表于 2017年6月21日 01:08:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/44659210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定