Source file misc/cgo/gmp/fib.go

     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  // +build ignore
     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  	big "."
    16  	"runtime"
    17  )
    18  
    19  func fibber(c chan *big.Int, out chan string, n int64) {
    20  	// Keep the fibbers in dedicated operating system
    21  	// threads, so that this program tests coordination
    22  	// between pthreads and not just goroutines.
    23  	runtime.LockOSThread()
    24  
    25  	i := big.NewInt(n)
    26  	if n == 0 {
    27  		c <- i
    28  	}
    29  	for {
    30  		j := <-c
    31  		out <- j.String()
    32  		i.Add(i, j)
    33  		c <- i
    34  	}
    35  }
    36  
    37  func main() {
    38  	c := make(chan *big.Int)
    39  	out := make(chan string)
    40  	go fibber(c, out, 0)
    41  	go fibber(c, out, 1)
    42  	for i := 0; i < 200; i++ {
    43  		println(<-out)
    44  	}
    45  }
    46  

View as plain text