Go并发编程

栏目: IT技术 · 发布时间: 5年前

常见并发模型

  • 进程 & 线程(Apache)C10K
  • 异步非阻塞(Nginx,Libevent,NodeJS) 复杂度高
  • 协程 (Golang,Erlang,Lua)

并发与并行

  • 并发:指同一时刻,系统通过调度,来回切换交替的运行多个任务,"看起来"是同时进行
  • 并行:指同一时刻,两个任务"真正的"同时进行

    Go并发编程

    图一.png

Golang并发实现

  • 程序并发执行(goroutine)
  • 多个goroutine间的数据同步和通信(channels)
  • 多个channel选择数据读取或写入(select)

Goroutine(程序并发执行)

foo() //执行函数foo,程序等待函数foo返回

go foo() //执行函数foo
bar() //不用等待foo返回

Channels(多个goroutine间的数据同步和通信)

c := make(chan string) //创建一个channel
go func() {
    time.Sleep(time.Second*1)
   c <- "hello world" //发送数据到channel中
}()
msg := <- c //阻塞直到接收到数据

Select(从多个channel中读取或写入数据)

select{
case v := <-c1:
    fmt.Println("channel 1 send",v)
case v := <-c2:
    fmt.Println("channel 2 send",v)
default: //可选
    fmt.Println("channel was ready")
}
//c1和c2同时有数据时,select随机选一个

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Sovereign Individual

The Sovereign Individual

James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00

Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具