chain.go 884 Bytes
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2009 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Pass numbers along a chain of threads.

package main

import (
10 11 12
	"runtime"
	"stdio"
	"strconv"
13 14 15 16 17 18 19 20 21
)

const N = 10
const R = 5

func link(left chan<- int, right <-chan int) {
	// Keep the links in dedicated operating system
	// threads, so that this program tests coordination
	// between pthreads and not just goroutines.
22
	runtime.LockOSThread()
23
	for {
24
		v := <-right
Russ Cox's avatar
Russ Cox committed
25
		stdio.Stdout.WriteString(strconv.Itoa(v) + "\n")
26
		left <- 1 + v
27 28 29 30
	}
}

func main() {
31 32 33
	leftmost := make(chan int)
	var left chan int
	right := leftmost
34
	for i := 0; i < N; i++ {
35 36
		left, right = right, make(chan int)
		go link(left, right)
37 38
	}
	for i := 0; i < R; i++ {
39 40
		right <- 0
		x := <-leftmost
Russ Cox's avatar
Russ Cox committed
41
		stdio.Stdout.WriteString(strconv.Itoa(x) + "\n")
42 43
	}
}