第06天(并发编程)_01

01_创建goroutine.go

package main
import (
    "fmt"
    "time"
)
func newTask() {
    for {
        fmt.Println("this is a newTask")
        time.Sleep(time.Second) //延时1s
    }
}
func main() {
    go newTask() //新建一个协程, 新建一个任务
    for {
        fmt.Println("this is a main goroutine")
        time.Sleep(time.Second) //延时1s
    }
}

02_主goroutine先退出.go

package main

import (
    "fmt"
    "time"
)
//主协程退出了,其它子协程也要跟着退出
func main() {
    go func() {
        i := 0
        for {
            i++
            fmt.Println("子协程 i = ", i)
            time.Sleep(time.Second)
        }

    }() //别忘了()
    i := 0
    for {
        i++
        fmt.Println("main i = ", i)
        time.Sleep(time.Second)

        if i == 2 {
            break
        }
    }
}

03_主协程先退出导致子协程没有来得及调用.go

package main

import (
    "fmt"
    "time"
)

//主协程退出了,其它子协程也要跟着退出
func main() {
    go func() {
        i := 0
        for {
            i++
            fmt.Println("子协程 i = ", i)
            time.Sleep(time.Second)
        }

    }() //别忘了()
}

04_Gosched的使用.go

package main
import (
    "fmt"
    "runtime"
)
func main() {
    go func() {
        for i := 0; i < 5; i++ {
            fmt.Println("go")
        }
    }()
    for i := 0; i < 2; i++ {
        //让出时间片,先让别的协议执行,它执行完,再回来执行此协程
        runtime.Gosched()
        fmt.Println("hello")
    }
}

05_Goexit的使用.go

package main

import (
    "fmt"
    "runtime"
)

func test() {
    defer fmt.Println("ccccccccccccc")
    //return //终止此函数
    runtime.Goexit() //终止所在的协程
    fmt.Println("dddddddddddddddddddddd")
}

func main() {
    //创建新建的协程
    go func() {
        fmt.Println("aaaaaaaaaaaaaaaaaa")
        //调用了别的函数
        test()
        fmt.Println("bbbbbbbbbbbbbbbbbbb")
    }() //别忘了()
    //特地写一个死循环,目的不让主协程结束
    for {
    }
}

06_GOMAXPROCS的使用.go

package main

import (
    "fmt"
    "runtime"
)
func main() {
    //n := runtime.GOMAXPROCS(1) //指定以1核运算
    n := runtime.GOMAXPROCS(4) //指定以4核运算
    fmt.Println("n = ", n)
    for {
        go fmt.Print(1)
        fmt.Print(0)
    }
}

07_多任务资源竞争问题.go

package main

import (
    "fmt"
    "time"
)

//定义一个打印机,参数为字符串,按每个字符打印
//打印机属于公共资源
func Printer(str string) {
    for _, data := range str {
        fmt.Printf("%c", data)
        time.Sleep(time.Second)
    }
    fmt.Printf("\n")
}

func person1() {
    Printer("hello")
}

func person2() {
    Printer("world")
}

func main() {
    //新建2个协程,代表2个人,2个人同时使用打印机
    go person1()
    go person2()

    //特地不让主协程结束,死循环
    for {

    }
}

08_通过channel实现同步.go

package main

import (
    "fmt"
    "time"
)

//全局变量,创建一个channel
var ch = make(chan int)

//定义一个打印机,参数为字符串,按每个字符打印
//打印机属于公共资源
func Printer(str string) {
    for _, data := range str {
        fmt.Printf("%c", data)
        time.Sleep(time.Second)
    }
    fmt.Printf("\n")
}

//person1执行完后,才能到person2执行
func person1() {
    Printer("hello")
    ch <- 666 //给管道写数据,发送
}

func person2() {
    <-ch //从管道取数据,接收,如果通道没有数据他就会阻塞
    Printer("world")
}

func main() {
    //新建2个协程,代表2个人,2个人同时使用打印机
    go person1()
    go person2()

    //特地不让主协程结束,死循环
    for {

    }
}

09_通过channel实现同步和数据交互.go

package main

import (
    "fmt"
    "time"
)

func main() {
    //创建channel
    ch := make(chan string)
    defer fmt.Println("主协程也结束")
    go func() {
        defer fmt.Println("子协程调用完毕")
        for i := 0; i < 2; i++ {
            fmt.Println("子协程 i = ", i)
            time.Sleep(time.Second)
        }
        ch <- "我是子协程,要工作完毕"
    }()
    str := <-ch //没有数据前,阻塞
    fmt.Println("str = ", str)
}

10_无缓冲的channel.go

package main

import (
    "fmt"
    "time"
)

func main() {
    //创建一个无缓存的channel
    ch := make(chan int, 0)

    //len(ch)缓冲区剩余数据个数, cap(ch)缓冲区大小
    fmt.Printf("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))

    //新建协程
    go func() {
        for i := 0; i < 3; i++ {
            fmt.Printf("子协程:i = %d\n", i)
            ch <- i //往chan写内容
        }
    }()

    //延时
    time.Sleep(2 * time.Second)

    for i := 0; i < 3; i++ {
        num := <-ch //读管道中内容,没有内容前,阻塞
        fmt.Println("num = ", num)
    }
}

11_有缓冲的channel.go

package main

import (
    "fmt"
    "time"
)

func main() {
    //创建一个有缓存的channel
    ch := make(chan int, 3)

    //len(ch)缓冲区剩余数据个数, cap(ch)缓冲区大小
    fmt.Printf("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))

    //新建协程
    go func() {
        for i := 0; i < 10; i++ {
            ch <- i //往chan写内容
            fmt.Printf("子协程[%d]: len(ch) = %d, cap(ch)= %d\n", i, len(ch), cap(ch))
        }
    }()

    //延时
    time.Sleep(2 * time.Second)

    for i := 0; i < 10; i++ {
        num := <-ch //读管道中内容,没有内容前,阻塞
        fmt.Println("num = ", num)
    }

}

12_关闭channel.go

package main

import (
    "fmt"
)

func main() {
    ch := make(chan int) //创建一个无缓存channel

    //新建一个goroutine
    go func() {
        for i := 0; i < 5; i++ {
            ch <- i //往通道写数据
        }
        //不需要再写数据时,关闭channel
        close(ch)
        //ch <- 666 //关闭channel后无法再发送数据

    }() //别忘了()

    for num := range ch {
        fmt.Println("num = ", num)
    }

}

func main01() {
    ch := make(chan int) //创建一个无缓存channel

    //新建一个goroutine
    go func() {
        for i := 0; i < 5; i++ {
            ch <- i //往通道写数据
        }
        //不需要再写数据时,关闭channel
        close(ch)
        //ch <- 666 //关闭channel后无法再发送数据

    }() //别忘了()

    for {
        //如果ok为true,说明管道没有关闭
        if num, ok := <-ch; ok == true {
            fmt.Println("num = ", num)
        } else { //管道关闭
            break
        }
    }

}

13_单向channel的特性.go

package main

//"fmt"

func main() {
    //创建一个channel, 双向的
    ch := make(chan int)

    //双向channel能隐式转换为单向channel
    var writeCh chan<- int = ch //只能写,不能读
    var readCh <-chan int = ch  //只能读,不能写

    writeCh <- 666 //写
    //<-writeCh //err,  invalid operation: <-writeCh (receive from send-only type chan<- int)

    <-readCh //读
    //readCh <- 666 //写, err,  invalid operation: readCh <- 666 (send to receive-only type <-chan int)

    //单向无法转换为双向
    //var ch2 chan int = writeCh //cannot use writeCh (type chan<- int) as type chan int in assignment

}

14_单向channel的应用.go

package main

import (
    "fmt"
)

//此通道只能写,不能读
func producer(out chan<- int) {
    for i := 0; i < 10; i++ {
        out <- i * i
    }
    close(out)
}

//此channel只能读,不能写
func consumer(in <-chan int) {
    for num := range in {
        fmt.Println("num = ", num)
    }
}

func main() {
    //创建一个双向通道
    ch := make(chan int)

    //生产者,生产数字,写入channel
    //新开一个协程
    go producer(ch) //channel传参,引用传递

    //消费者,从channel读取内容,打印
    consumer(ch)
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,812评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,626评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,144评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,052评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,925评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,035评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,461评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,150评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,413评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,501评论 2 307
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,277评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,159评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,528评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,868评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,143评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,407评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,615评论 2 335

推荐阅读更多精彩内容