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. Spring AOP高级——源码实现(3)AopProxy代理对象之JDK动态代理的创建过程

    spring-aop-4.3.7.RELEASE  在<Spring AOP高级——源码实现(1)动态代理技术>中介绍了两种动态代理技术,当然在Spring AOP中代理对象的生成也是运用 ...

  2. JavaScript学习笔记(十二)——箭头函数(Arrow Function)

    在学习廖雪峰前辈的JavaScript教程中,遇到了一些需要注意的点,因此作为学习笔记列出来,提醒自己注意! 如果大家有需要,欢迎访问前辈的博客https://www.liaoxuefeng.com/ ...

  3. 【转】【JAVA应用】多线程断点下载

    [转自] 光仔December http://blog.csdn.net/acmman 问题:多线程下载的好处? 多线程下载比单线程下载快,主要的原因是采用多线程下载,可以抢占更多的服务器资源.抢占C ...

  4. Android 软键盘的显示和隐藏,这样操作就对了

    一.前言 如果有需要用到输入的地方,通常会有需要自动弹出或者收起软键盘的需求.开篇明义,本文会讲讲弹出和收起软键盘的一些细节,最终还会从源码进行分析. 想要操作软键盘,需要使用到 InputMetho ...

  5. C++反汇编第二讲,不同作用域下的构造和析构的识别

    C++反汇编第二讲,不同作用域下的构造和析构的识别 目录大纲: 1.全局(静态)对象的识别,(全局静态全局一样的,都是编译期间检查,所以当做全局对象看即可.) 1.1 探究本质,理解构造和析构的生成, ...

  6. Python入门 - 面向对象

    python很好的支持面向对象编程,本节主讲类的定义,类的构造方法,类的继承与方法重写,类的多继承. 一.类的定义 class Myclass() : def prt(self, str) : pri ...

  7. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十一)redis密码设置、安全设置

    警惕 前一篇文章<Spring+SpringMVC+MyBatis+easyUI整合进阶篇(九)Linux下安装redis及redis的常用命令和操作>主要是一个简单的介绍,针对redis ...

  8. Wannafly挑战赛5 补题

    A 珂朵莉与宇宙 题目链接: https://www.nowcoder.com/acm/contest/36/A 思路: 科学暴力:枚举前缀和,同时计算前缀和里面可能出现的完全平方数,匹配前缀和 与完 ...

  9. 一句话搞定webmap(一)——轻地图组件

    摘要: 遥想当年.在APP中增加LBS元素相当困难:要刻苦学习java,要刻苦学习iOS开发,要刻苦学习javascript-- 而现在.要制作一张地图真是越来越easy了!居然仅仅须要一句话.就能够 ...

  10. Ubuntu1204 vim中文乱码解决方法

    加入中文字符编码 sudo vi /var/lib/locales/supported.d/local #加入以下的中文字符集 zh_CN.GBK GBK zh_CN.GB2312 GB2312 zh ...