exploit
1/28/2019 - 12:01 PM

goroutine

package main

import (
	"fmt"
	"time"
)
func print(name string){
	fmt.Println(name,time.Now())
	time.Sleep(4 * time.Second)
}


func main() {
	arrs := []string{"Hello","World"}
	arrs3 := append(arrs,"HHAHH")
	
	for _,name := range arrs3 {
		//fmt.Println(name)
		go print(name)
	}
	
	time.Sleep(5 * time.Second)
	fmt.Println("Done",time.Now())
	
}
package main

import (
	"fmt"
	"time"
)


func print(name string,c chan string){
	fmt.Println(name,"start",time.Now())
	time.Sleep(4 * time.Second)
	// 接受channal,并处理数据,发出信号
	c <- name

}


func main() {
	arrs := []string{"Hello","World"}
	arrs3 := append(arrs,"HHAHH")
	
	// 新建一个channal
	c:=make(chan string)
	
	for _,name := range arrs3 {
		// 传入通道和数据,开始处理
		go print(name,c)

	}
	for i:=0;i<len(arrs3);i++{
		// 接受传出来的信号
		name := <- c
		fmt.Println("Receved",name,time.Now())
		
		
	}
	// 结束
	fmt.Println("Done",time.Now())
	
}
package main

import (
	"fmt"
	"time"
	"math/rand"
)


func print(name string,c chan string){
	wait := time.Duration(rand.Intn(3000)) * time.Millisecond
	fmt.Println(name,"start",time.Now())
	fmt.Println(wait)
	time.Sleep(wait)
	
	// 接受channal,并处理数据,发出信号
	c <- name

}


func main() {
	arrs := []string{"Hello","World"}
	arrs3 := append(arrs,"HHAHH")
	
	// 新建一个channal
	c := make(chan string)
	timeout := time.After(3*time.Second)
	
	for _,name := range arrs3 {
		// 传入通道和数据,开始处理
		go print(name,c)

	}
	for i:=0;i<len(arrs3);i++{
		// 接受传出来的信号
		select {
		// 选择两种情况,一个是正常传出来的值
		case n := <- c:
			fmt.Println("done",n)
			
		// 如果timeout 时间到了,还没有正常的值传出来,就是用timeout的值来结束这一切
		case <-timeout:
			fmt.Println("My patience ran out ")
			return 
		}
		
		
	}
	// 结束
	fmt.Println("Done",time.Now())
	
}
package main

import (
	"fmt"
	"time"
	
)
// pipline 

func pipline1(downstream chan string){
	arrs := [] string {"Hello","World","nihao","shijie"}
	for _,v :=  range arrs {
		downstream <- v
	} 
	// 已经没有数据要传递给下一个strema, 关掉
	close(downstream)
	
}


func pipline2(upstream,downstream chan string){
	for {
		item,ok:= <-upstream 
		// !ok 代表没有数据可以传输了。
		if !ok {
			close(downstream)
			return 
		}
		
		downstream <- item 
		
		
	}
}

func pipline3(upstream chan string){
	for {
		item,ok:= <-upstream
		if !ok{
			return 
		}
		fmt.Println(item,time.Now())
	}
}


func main() {
	c1 := make(chan string)
	c2 := make(chan string)
	go pipline1(c1)
	go pipline2(c1,c2)
	pipline3(c2)
}