Created
April 7, 2019 12:24
-
-
Save penglongli/7f8eaee1fdec19e55097bb1d041dcac3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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