github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/misc/cgo/stdio/chain.go (about)

     1  // cmpout
     2  
     3  // Copyright 2009 The Go Authors.  All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // +build ignore
     8  
     9  // Pass numbers along a chain of threads.
    10  
    11  package main
    12  
    13  import (
    14  	"../stdio"
    15  	"runtime"
    16  	"strconv"
    17  )
    18  
    19  const N = 10
    20  const R = 5
    21  
    22  func link(left chan<- int, right <-chan int) {
    23  	// Keep the links in dedicated operating system
    24  	// threads, so that this program tests coordination
    25  	// between pthreads and not just goroutines.
    26  	runtime.LockOSThread()
    27  	for {
    28  		v := <-right
    29  		stdio.Stdout.WriteString(strconv.Itoa(v) + "\n")
    30  		left <- 1 + v
    31  	}
    32  }
    33  
    34  func main() {
    35  	leftmost := make(chan int)
    36  	var left chan int
    37  	right := leftmost
    38  	for i := 0; i < N; i++ {
    39  		left, right = right, make(chan int)
    40  		go link(left, right)
    41  	}
    42  	for i := 0; i < R; i++ {
    43  		right <- 0
    44  		x := <-leftmost
    45  		stdio.Stdout.WriteString(strconv.Itoa(x) + "\n")
    46  	}
    47  }