| 1 |
// Copyright 2009 The Go 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 |
//go:build test_run |
| 6 |
|
| 7 |
// Compute Fibonacci numbers with two goroutines |
| 8 |
// that pass integers back and forth. No actual |
| 9 |
// concurrency, just threads and synchronization |
| 10 |
// and foreign code on multiple pthreads. |
| 11 |
|
| 12 |
package main |
| 13 |
|
| 14 |
import ( |
| 15 |
"runtime" |
| 16 |
"strconv" |
| 17 |
|
| 18 |
"cgostdio/stdio" |
| 19 |
) |
| 20 |
|
| 21 |
func fibber(c, out chan int64, i int64) { |
| 22 |
// Keep the fibbers in dedicated operating system |
| 23 |
// threads, so that this program tests coordination |
| 24 |
// between pthreads and not just goroutines. |
| 25 |
runtime.LockOSThread() |
| 26 |
|
| 27 |
if i == 0 { |
| 28 |
c <- i |
| 29 |
} |
| 30 |
for { |
| 31 |
j := <-c |
| 32 |
stdio.Stdout.WriteString(strconv.FormatInt(j, 10) + "\n") |
| 33 |
out <- j |
| 34 |
<-out |
| 35 |
i += j |
| 36 |
c <- i |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
func main() { |
| 41 |
c := make(chan int64) |
| 42 |
out := make(chan int64) |
| 43 |
go fibber(c, out, 0) |
| 44 |
go fibber(c, out, 1) |
| 45 |
<-out |
| 46 |
for i := 0; i < 90; i++ { |
| 47 |
out <- 1 |
| 48 |
<-out |
| 49 |
} |
| 50 |
} |