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. Java父线程(或是主线程)等待所有子线程退出

    static void testLock1(){ final AtomicInteger waitCount = new AtomicInteger(30000); final Object wait ...

  2. 张高兴的 Xamarin.Forms 开发笔记:TapGestureRecognizer 的简单介绍与应用

    最近很少写应用了,一直在忙关于 ASP.NET 的东西(哈欠...).抽点时间对 TapGestureRecognizer 做点总结. 一.简介 TapGestureRecognizer 就是对 Ta ...

  3. 初试pyspider

    灵感来源: https://zhuanlan.zhihu.com/p/31421316 抓取页面: https://www.nvshens.com/tag/new/ 页面分析: 首页获取所有图片详情页 ...

  4. LINQ学习系列-----1.3 扩展方法

    这篇内容继续接着昨天的Lambda表达式的源码继续下去.昨天讲了Lambda表达式,此篇讲扩展方法,这两点都是Linq带来的新特性.    一.扩展方法介绍   废话不多说,先上源码截图: 上图中Ge ...

  5. opencv摄像头捕获图像

    #include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using namespace st ...

  6. selenium 使用xpath定位不到

    <button id="" class="btn btn-some" type="submit"> <i class=&q ...

  7. C语言结构体1.1

    结构体组成 struct 结构体名: 类型名  成员名: 建立结构体 结构体名 类型名 { 成员: }: 建立一个关于学生信息的结构体(名字,年龄,性别,学号,成绩): 结构体定义 //结构体声明 s ...

  8. Java编程学习技巧和方法总结

    干货:必须要有反馈,不断调整,多读书,多些笔记. 解释:不练习你以为你能掌握?笑话,只有自己根据一个个小目标不断的敲,运行,给予你反馈,这样才会真的进步. 纸上谈Java,是永远停止在口.   关于笔 ...

  9. CCF-201403-1-相反数

    问题描述 试题编号: 201403-1 试题名称: 相反数 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 有 N 个非零且各不相同的整数.请你编一个程序求出它们中有多少对相反 ...

  10. c++邻接表存储图(无向),并用广度优先和深度优先遍历(实验)

    一开始我是用c写的,后面才发现广搜要用到队列,所以我就直接使用c++的STL队列来写, 因为不想再写多一个队列了.这次实验写了两个多钟,因为要边写边思考,太菜了哈哈. 主要参考<大话数据结构&g ...