Search code examples
gooperating-systemsemaphoresynchronoussequential

Concurrency semaphore sequential execution


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


Solution

  • 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.