| 1 | // Copyright ©2011-2013 The bíogo Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package concurrent_test |
| 6 | |
| 7 | import ( |
| 8 | "github.com/biogo/biogo/concurrent" |
| 9 | |
| 10 | "fmt" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | type SlowCounter []int |
| 15 | |
| 16 | func (c SlowCounter) Slice(i, j int) concurrent.Mapper { return c[i:j] } |
| 17 | func (c SlowCounter) Len() int { return len(c) } |
| 18 | |
| 19 | func (c SlowCounter) Operation() (r interface{}, err error) { |
| 20 | var sum int |
| 21 | for _, v := range c { |
| 22 | sum += v |
| 23 | time.Sleep(1e8) |
| 24 | } |
| 25 | return sum, nil |
| 26 | } |
| 27 | |
| 28 | func ExamplePromiseMap() { |
| 29 | c := SlowCounter{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} |
| 30 | |
| 31 | p := concurrent.PromiseMap(c, 1, 2) |
| 32 | fmt.Println("Waiting...") |
| 33 | request1 := <-p.Wait() |
| 34 | if request1.Err != nil { |
| 35 | fmt.Println(request1.Err) |
| 36 | } else { |
| 37 | fmt.Println(request1.Value) |
| 38 | } |
| 39 | request2 := <-p.Wait() |
| 40 | if request2.Err != nil { |
| 41 | fmt.Println(request2.Err) |
| 42 | } else { |
| 43 | fmt.Println(request2.Value) |
| 44 | } |
| 45 | |
| 46 | // Output: |
| 47 | // Waiting... |
| 48 | // [3 7 11 15 19] |
| 49 | // [3 7 11 15 19] |
| 50 | } |