github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/misc/cgo/stdio/testdata/fib.go (about)

     1  // run -tags=use_go_run
     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 test_run
     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  	"runtime"
    18  	"strconv"
    19  
    20  	"cgostdio/stdio"
    21  )
    22  
    23  func fibber(c, out chan int64, i int64) {
    24  	// Keep the fibbers in dedicated operating system
    25  	// threads, so that this program tests coordination
    26  	// between pthreads and not just goroutines.
    27  	runtime.LockOSThread()
    28  
    29  	if i == 0 {
    30  		c <- i
    31  	}
    32  	for {
    33  		j := <-c
    34  		stdio.Stdout.WriteString(strconv.FormatInt(j, 10) + "\n")
    35  		out <- j
    36  		<-out
    37  		i += j
    38  		c <- i
    39  	}
    40  }
    41  
    42  func main() {
    43  	c := make(chan int64)
    44  	out := make(chan int64)
    45  	go fibber(c, out, 0)
    46  	go fibber(c, out, 1)
    47  	<-out
    48  	for i := 0; i < 90; i++ {
    49  		out <- 1
    50  		<-out
    51  	}
    52  }