chain.go 938 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. // Pass numbers along a chain of threads.
  7. package main
  8. import (
  9. "runtime"
  10. "strconv"
  11. "cgostdio/stdio"
  12. )
  13. const N = 10
  14. const R = 5
  15. func link(left chan<- int, right <-chan int) {
  16. // Keep the links in dedicated operating system
  17. // threads, so that this program tests coordination
  18. // between pthreads and not just goroutines.
  19. runtime.LockOSThread()
  20. for {
  21. v := <-right
  22. stdio.Stdout.WriteString(strconv.Itoa(v) + "\n")
  23. left <- 1 + v
  24. }
  25. }
  26. func main() {
  27. leftmost := make(chan int)
  28. var left chan int
  29. right := leftmost
  30. for i := 0; i < N; i++ {
  31. left, right = right, make(chan int)
  32. go link(left, right)
  33. }
  34. for i := 0; i < R; i++ {
  35. right <- 0
  36. x := <-leftmost
  37. stdio.Stdout.WriteString(strconv.Itoa(x) + "\n")
  38. }
  39. }