zoukankan      html  css  js  c++  java
  • Golang学习(用代码来学习)

    
    /**
    一个用来进行go routine的函数
     */
    func print_something(msg string){
    	for i:= 0;i < 5;i++{
    		time.Sleep(1 * time.Second)
    		fmt.Println(msg)
    	}
    }
    
    /**
    异步相加,并将结果放在通道中
     */
    func add_async(a int, b int, ch *chan int){
    	time.Sleep(2 * time.Second)
    	sum := a+ b
    	*ch <- sum
    }
    
    /**
    sleep一会儿
     */
    func sleep_sometime(){
    	fmt.Println("start sleeping.....")
    	time.Sleep(2 * time.Second)
    	fmt.Println("end sleeping.....")
    }
    
    /**
    goroutine的学习
    通过go来指定一个goroutime
    */
    func goroutine_test() {
    	print_start_seperator("goroutine_test")
    	//启动一个go routine
    	go print_something("hello")
    	print_something("world")
    
    	//执行一个异步加法
    	var ch = make(chan int)
    	go add_async(1,2,&ch)
    	//从通道等待结果,如果不返回,就会一直阻塞着
    	res := <- ch
    	fmt.Printf("async add res:%d
    ", res)
    
    	//通道也可以初始化缓冲区
    	var ch2 = make(chan int, 2)
    	ch2 <- 1
    	ch2 <- 2
    	fmt.Printf("ch2 first:%d
    ", <- ch2)
    	fmt.Printf("ch2 second:%d
    ", <- ch2)
    
    	var ch3 = make(chan int, 10)
    	for i:= 0; i < 10;i++{
    		ch3 <- i
    	}
    	close(ch3)
    
    	//如果通道不关闭的话,那么range就会一直卡着,从这里的代码也可以看出来,close掉channel后数据并不会消失,只是会让range
    	//这种迭代不会一直阻塞而等待新数据
    	for item := range ch3{
    		fmt.Printf("%d	", item)
    	}
    	fmt.Println("")
    
    	//如果说我们不等待goroutine结束,那么当函数结束后,goroutine会直接被系统结束,不会在继续执行,这点和其他语言的线程不太一样 ,可以通过channel的方式
    	//来完成同步
    	go sleep_sometime()
    	//为了确保我们的goroutine能执行到
    	time.Sleep(10 * time.Millisecond)
    
    	print_end_seperator()
    }
    
    func print_start_seperator(key_word string) {
    	fmt.Printf("**********************************************%s***************************************************
    ", key_word)
    }
    
    func print_end_seperator() {
    	fmt.Println("****************************************************************************************************")
    }
    
    
  • 相关阅读:
    [ZOJ 4062][2018ICPC青岛站][Plants vs. Zombies]
    [Wannafly挑战赛28][B msc和mcc][预处理+枚举]
    [codeforces Mail.Ru Cup 2018 Round 1 D][ xor 操作]
    [codeforces round#475 div2 ][C Alternating Sum ]
    [zoj4045][思维+dfs]
    [zoj4046][树状数组求逆序(强化版)]
    费马大定理以及求解a^2+b^2=c^2的奇偶数列法则
    【HDOJ3567】【预处理bfs+映射+康拓展开hash】
    POJ1279 Art Gallery 多边形的核
    第八周 Leetcode 44. Wildcard Matching 水题 (HARD)
  • 原文地址:https://www.cnblogs.com/seancheer/p/13167998.html
Copyright © 2011-2022 走看看