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