1、goroutine线程

  goroutine是一个轻量级的执行线程。假设有一个函数调用f(s),要在goroutine中调用此函数,请使用go f(s)。 这个新的goroutine将与调用同时执行。

  示例代码如下:

 package main

 import "fmt"

 func f(from string) {
for i := ; i < ; i++ {
fmt.Println(from, ":", i)
}
} func main() { // Suppose we have a function call `f(s)`. Here's how
// we'd call that in the usual way, running it
// synchronously.
f("direct") // To invoke this function in a goroutine, use
// `go f(s)`. This new goroutine will execute
// concurrently with the calling one.
go f("goroutine") // You can also start a goroutine for an anonymous
// function call.
go func(msg string) {
fmt.Println(msg)
}("going") // Our two function calls are running asynchronously in
// separate goroutines now, so execution falls through
// to here. This `Scanln` code requires we press a key
// before the program exits.
var input string
fmt.Scanln(&input)
fmt.Println("done")
}

  执行上面代码,将得到以下输出结果

 direct :
direct :
direct :
goroutine :
goroutine :
goroutine :
going

2、通道

  通道是连接并发goroutine的管道。可以从一个goroutine向通道发送值,并在另一个goroutine中接收到这些值。

 package main

 import "fmt"

 func main() {

     // Create a new channel with `make(chan val-type)`.
// Channels are typed by the values they convey.
messages := make(chan string) // _Send_ a value into a channel using the `channel <-`
// syntax. Here we send `"ping"` to the `messages`
// channel we made above, from a new goroutine.
go func() { messages <- "ping" }()//使用"<-"向通道发送消息 // The `<-channel` syntax _receives_ a value from the
// channel. Here we'll receive the `"ping"` message
// we sent above and print it out.
msg := <-messages//"从通道读取数据"
fmt.Println(msg)
}

  默认情况下,通道是未缓冲的,意味着如果有相应的接收(<- chan)准备好接收发送的值,它们将只接受发送(chan <- )。使用make的第二个参数指定缓冲大小

 package main

 import "fmt"

 func main() {

     // Here we `make` a channel of strings buffering up to
// 2 values.
messages := make(chan string, ) // Because this channel is buffered, we can send these
// values into the channel without a corresponding
// concurrent receive.
messages <- "buffered"
messages <- "channel" // Later we can receive these two values as usual.
fmt.Println(<-messages)
fmt.Println(<-messages)
}

3、通道同步

 package main

 import "fmt"
import "time" // This is the function we'll run in a goroutine. The
// `done` channel will be used to notify another
// goroutine that this function's work is done.
func worker(done chan bool) {
fmt.Print("working...")
time.Sleep(time.Second)
fmt.Println("done") // Send a value to notify that we're done.
done <- true
} func main() { // Start a worker goroutine, giving it the channel to
// notify on.
done := make(chan bool, )
go worker(done) // Block until we receive a notification from the
// worker on the channel.
<-done
}

  当使用通道作为函数参数时,可以指定通道是否仅用于发送或接收值。这种特殊性增加了程序的类型安全性。chan<-表示发送,<-chan表示接收

4、select

  每个通道将在一段时间后开始接收值,以模拟阻塞在并发goroutines中执行的RPC操作。我们将使用select同时等待这两个值,在每个值到达时打印它们。

 package main

 import "time"
import "fmt" func main() { // For our example we'll select across two channels.
c1 := make(chan string)
c2 := make(chan string) // Each channel will receive a value after some amount
// of time, to simulate e.g. blocking RPC operations
// executing in concurrent goroutines.
go func() {
time.Sleep(time.Second * )
c1 <- "one"
}()
go func() {
time.Sleep(time.Second * )
c2 <- "two"
}() // We'll use `select` to await both of these values
// simultaneously, printing each one as it arrives.
for i := ; i < ; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}

5、相关文章

  Go超时(timeouts)实例

  Go非阻塞通道操作实例:使用selectdefault子句来实现非阻塞发送,接收

  Go关闭通道实例:close直接关闭通道

  Go通道范围实例:通道关闭了,还可以接收通道中的数据

如果您觉得文章不错,不妨给个打赏,写作不易,感谢各位的支持。您的支持是我最大的动力,谢谢!!! 

 

很重要--转载声明

  1. 本站文章无特别说明,皆为原创,版权所有,转载时请用链接的方式,给出原文出处。同时写上原作者:朝十晚八 or Twowords
  2. 如要转载,请原文转载,如在转载时修改本文,请事先告知,谢绝在转载时通过修改本文达到有利于转载者的目的。

go实例之轻量级线程goroutine、通道channel与select的更多相关文章

  1. Go part 8 并发编程,goroutine, channel

    并发 并发是指的多任务,并发编程含义比较广泛,包含多线程.多进程及分布式程序,这里记录的并发是属于多线程编程 Go 从语言层面上支持了并发的特性,通过 goroutine 来完成,goroutine ...

  2. golang协程——通道channel阻塞

    新的一年开始了,不管今天以前发生了什么,向前看,就够了. 说到channel,就一定要说一说线程了.任何实际项目,无论大小,并发是必然存在的.并发的存在,就涉及到线程通信.在当下的开发语言中,线程通讯 ...

  3. 「一闻秒懂」你了解goroutine和channel吗?

    开源库「go home」聚焦Go语言技术栈与面试题,以协助Gopher登上更大的舞台,欢迎go home~ 背景介绍 大家都知道进程是操作系统资源分配的基本单位,有独立的内存空间,线程可以共享同一个进 ...

  4. Go--关于 goroutine、channel

    Go--关于 goroutine.channel goroutine 协程是一种轻量化的线程,由Go编译器进行优化. Go协程具有以下特点: 有独立的栈空间 共享程序堆中的空间 调度由用户控制 如果主 ...

  5. go并发之goroutine和channel,并发控制入门篇

    并发的概念及其重要性 这段是简单科普,大佬可以跳过 并发:并发程序指同时进行多个任务的程序.在操作系统中,是指一个时间段中有几个程序都处于已启动运行到运行完毕之间,且这几个程序都是在同一个处理机上运行 ...

  6. Golang并发编程——goroutine、channel、sync

    并发与并行 并发和并行是有区别的,并发不等于并行. 并发 两个或多个事件在同一时间不同时间间隔发生.对应在Go中,就是指多个 goroutine 在单个CPU上的交替运行. 并行 两个或者多个事件在同 ...

  7. TODO:Go语言goroutine和channel使用

    TODO:Go语言goroutine和channel使用 goroutine是Go语言中的轻量级线程实现,由Go语言运行时(runtime)管理.使用的时候在函数前面加"go"这个 ...

  8. [转帖]go 的goroutine 以及 channel 的简介.

    进程,线程的概念在操作系统的书上已经有详细的介绍.进程是内存资源管理和cpu调度的执行单元.为了有效利用多核处理器的优势,将进程进一步细分,允许一个进程里存在多个线程,这多个线程还是共享同一片内存空间 ...

  9. 九、goroutine和channel

    进程和线程 A)进程是程序在操作系统中的一次执行过程,系统进行资源分配和调度的一个独立单元 B)线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位 C)一个进 ...

随机推荐

  1. AutoCAD.net支持后台线程-Socket服务端

    最近因为公司项目的需求,CAD作为服务端在服务器中常驻运行,等待客户端远程发送执行任务的指令,最终确认用Socket-tcp通讯,CAD需要实时监听客户端发送的消息,这时就需要开启线程执行Socket ...

  2. JQuery使用笔记

    1.选择器 id选择器: $('#btnShow') class选择器: $('.banner') tag选择器: $('input') 2.常用方法 取 / 设value: $('#btnShow' ...

  3. 提高运维效率(二)桌面显示IP

    运维人员远控电脑询问IP时,总要告诉用户找ip的步骤,岂不很烦? 以下方法直观地把ip地址显示在桌面上,再做个入职培训,即可提高运维效率. 1.  下载bginfo.exe软件,放到域控下的netlo ...

  4. 深入浅出多线程——ReentrantLock (一)

    ReentrantLock是一个排它重入锁,与synchronized关键字语意类似,但比其功能更为强大.该类位于java.util.concurrent.locks包下,是Lock接口的实现类.基本 ...

  5. 2017计算机学科夏令营上机考试-B编码字符串

    B:编码字符串 总时间限制:  1000ms 内存限制:  65536kB 描述 在数据压缩中,一个常用的方法是行程长度编码压缩.对于一个待压缩的字符串,我们可以依次记录每个字符及重复的次数.例如,待 ...

  6. Solidity教程系列1 - 类型介绍

    现在的Solidity中文文档,要么翻译的太烂,要么太旧,决定重新翻译下,再加上代码事例讲解. 写在前面 Solidity是以太坊智能合约编程语言,阅读本文前,你应该对以太坊.智能合约有所了解, 如果 ...

  7. Linux 链接详解----静态链接实例分析

    由Linux链接详解(1)中我们简单的分析了静态库的引用解析和重定位的内容, 下面我们结合实例来看一下静态链接重定位过程. /* * a.c */ ; void add(int c); int mai ...

  8. [安全]PHP能引起安全的函数

    php中需要禁用以下函数来提高安全性 打开php.ini  找到 disable_functions .然后禁用以下函数 [C] 纯文本查看 复制代码 ? 1 disable_functions = ...

  9. java 接口测试

    学习java 时间也不算太长,大学有点基础,学起来也顺手多了,其实我感觉更是因为学习完python之后,在学习别的语言的时候就简单多了,几乎所有的语言学起来都差不多.前几篇写过的都是python接口测 ...

  10. 怎么配置Jupyter Notebook默认启动目录?

    前言 系统环境:win10 x64:跟环境也没啥关系,在LInux下也一样... 前段时间重换了系统后,发现Jupyter Notebook的默认启动目录不太对呀,所以,就翻到了以前的笔记,还是记在这 ...