fib.go 989 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // run -tags=use_go_run
  2. // Copyright 2009 The Go Authors. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. // +build test_run
  6. // Compute Fibonacci numbers with two goroutines
  7. // that pass integers back and forth. No actual
  8. // concurrency, just threads and synchronization
  9. // and foreign code on multiple pthreads.
  10. package main
  11. import (
  12. "runtime"
  13. "strconv"
  14. "cgostdio/stdio"
  15. )
  16. func fibber(c, out chan int64, i int64) {
  17. // Keep the fibbers in dedicated operating system
  18. // threads, so that this program tests coordination
  19. // between pthreads and not just goroutines.
  20. runtime.LockOSThread()
  21. if i == 0 {
  22. c <- i
  23. }
  24. for {
  25. j := <-c
  26. stdio.Stdout.WriteString(strconv.FormatInt(j, 10) + "\n")
  27. out <- j
  28. <-out
  29. i += j
  30. c <- i
  31. }
  32. }
  33. func main() {
  34. c := make(chan int64)
  35. out := make(chan int64)
  36. go fibber(c, out, 0)
  37. go fibber(c, out, 1)
  38. <-out
  39. for i := 0; i < 90; i++ {
  40. out <- 1
  41. <-out
  42. }
  43. }