1

I am thinking my result order should be the same as the input, is it possible to in go routine?

I implement like this:

package main

import "fmt"
import "time"

func worker(id int, jobs <-chan int, results chan<- int) {
  for j := range jobs {
    time.Sleep(time.Second)
    results <- j * 2
  }
}

func main() {
  jobs := make(chan int, 100)
  results := make(chan int, 100)

  for w := 1; w <= 3; w++ {
    go worker(w, jobs, results)
  }

  for j := 1; j <= 5; j++ {
    jobs <- j
  }
  close(jobs)

  // Finally we collect all the results of the work.
  // But somehow I want to keep the order
  for a := 1; a <= 5; a++ {
    fmt.Println(<-results) // actually, I want to make it 2, 4, 6, 8, 10
  }
}

run it here

roger
  • 9,063
  • 20
  • 72
  • 119
  • 1
    Why did you implement concurrent code if you need it to actually be serial? – zerkms May 05 '17 at 06:59
  • 1
    How about attaching a sequence number to each job, ordering them, and then sorting them when all the concurrent code has finished? – Vervious May 05 '17 at 07:06

1 Answers1

-2

Must keep results order at worker func. goroutine run no ordered. set results must keep order.

package main

import "fmt"
import "time"
import "sync/atomic"

var pivot uint32 = 1

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        time.Sleep(time.Second)

        for {
            if n := atomic.LoadUint32(&pivot); int(n) == j {
                results <- j * 2
                atomic.AddUint32(&pivot, 1)
                break
            }
            time.Sleep(time.Millisecond)
        }
    }
}

func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)

    // Finally we collect all the results of the work.
    // But somehow I want to keep the order
    for a := 1; a <= 5; a++ {
        fmt.Println(<-results) // actually, I want to make it 2, 4, 6, 8, 10
    }
}

run it here!

jame2981
  • 51
  • 1
  • 6