2017-05-05 53 views
0

我在想我的結果順序應該與輸入相同,是否有可能在進行例行公事?可以在輸入順序中收集goroutine結果嗎?

我實現這樣的:

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 
    } 
} 

來看,它here

+1

爲什麼你實現併發代碼,如果你需要它實際上是串行? – zerkms

+1

如何爲每個作業附加序列號,排序它們,然後在所有併發代碼完成時對它們進行排序? – Vervious

回答

-2

必須保持成果以便在工人FUNC。 goroutine運行沒有命令。設定結果必須保持順序。

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 
    } 
} 

運行它here

相關問題