Golang goroutine协程(一) 编写第一个并发处理的程序

package main

import (
    "fmt"
    "runtime"
    "sync"
)

var wg sync.WaitGroup //它是一个计数的信号量

func SayHi(s string) {
    defer wg.Done() //每一个goroutine的函数执行完之后,就调用Done方法对计数器减1
    for i := 0; i < 50000; i++ {
        //runtime.Gosched()表示让CPU把时间片让给别人,下次某个时候继续恢复执行该goroutine
        runtime.Gosched()
        fmt.Println(i, s)
    }
}

func main() {
    //要根据电脑的实际物理核数调整参数4的大小,如果不是多核的,设置再多的逻辑处理器个数也没用
    runtime.GOMAXPROCS(4) //4表示设置的逻辑处理器个数,4 ≤ runtime.NumCPU(), 其中NumCPU()是CPU的物理内核个数
    wg.Add(2)             //先是使用Add方法设置计数器为2
    go SayHi("world")
    go SayHi("hello")
    //Wait方法如果计数器大于0,就会阻塞主进程结束
    //假如主进程结束了,上面的go协程还没来得及输出一个结果,整个程序就运行结束了
    wg.Wait()
    fmt.Println("finished") //main函数里执行的代码都是主进程代码
}

Golang goroutine协程(一) 编写第一个并发处理的程序

Golang goroutine协程(一) 编写第一个并发处理的程序

Golang goroutine协程(一) 编写第一个并发处理的程序

[[email protected] ~]# tail -2000 hello.txt|awk '{print NR,$0}'|xargs -n12  ##快速查看hello.txt最后2000行输出结果

[[email protected] ~]# awk '{printf"%s %s\t\t%s",NR,$0,NR%5?"":"\n"}' hello.txt

Golang goroutine协程(一) 编写第一个并发处理的程序[[email protected] ~]#cat > myprint.format
{    if(NR%4 == 0)
         printf("%s%s",NR" ",$0 "\n")
    else
         printf("%s%s",NR" ",$0 "\t""\t")
}

[[email protected] ~]# more myprint.format
{    if(NR%4 == 0)
         printf("%s%s",NR" ",$0 "\n")
    else
         printf("%s%s",NR" ",$0 "\t""\t")
}

[[email protected] ~]# awk -f myprint.format hello.txt

Golang goroutine协程(一) 编写第一个并发处理的程序