The Seven Year Itch.

MENU

Go语言学习之 - 简单的并发程序

January 16, 2018 • Read: 293 • Go

  • 简单的并发
package main
import (
    . "fmt"
     "time"
)

func main(){
    for i :=0; i < 5; i++ {
        go printHelloWorld(i) // go starts goroutine
    }
    time.Sleep(time.Millisecond)
}

func printHelloWorld(i int){
    // go 语言中没有while,for不给任何条件的时候就类似死循环
    for {
       Printf("go run hello world %d",i) 
    }
    
}
  • 互相通信并发
package main

import (
    . "fmt"
)

func main() {
    ch := make(chan string)
    for i := 0; i < 1; i++ {
        go printHelloWorld(i, ch) // go starts goroutine "go" 开启并发
    }

    for {
        msg := <-ch
        Println(msg)
    }
}

func printHelloWorld(i int, ch chan string) {
    // chan
    for {
        ch <- Sprintf("go run helloWorld %d \n", i)
    }
}
Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code