Skip to content

Instantly share code, notes, and snippets.

@penglongli
Created April 7, 2019 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penglongli/7f8eaee1fdec19e55097bb1d041dcac3 to your computer and use it in GitHub Desktop.
Save penglongli/7f8eaee1fdec19e55097bb1d041dcac3 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
type Node struct {
sig chan int
str string
prev *Node
}
var (
lastOrder = 3
num = 10
wg sync.WaitGroup
)
func main() {
n1 := Node{make(chan int), "A", nil}
n2 := Node{make(chan int), "B", &n1}
n3 := Node{make(chan int), "C", &n2}
n1.prev = &n3
wg.Add(3)
go print(&n1, 1)
go print(&n2, 2)
go print(&n3, 3)
wg.Wait()
}
func print(node *Node, order int) {
defer wg.Done()
for i := 0; i < num; i++ {
if i == 0 && order == 1 {
fmt.Println(node.str)
node.sig <- 1
continue
}
<- node.prev.sig
fmt.Println(node.str)
if i == num-1 && order == lastOrder {
break
}
node.sig <- 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment