首页 技术 正文
技术 2022年11月14日
0 收藏 817 点赞 2,898 浏览 3251 个字

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通道范围实例:通道关闭了,还可以接收通道中的数据

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


 

go实例之轻量级线程goroutine、通道channel与select go实例之轻量级线程goroutine、通道channel与select

很重要–转载声明

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

奋斗中的无名小卒。。。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,498
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298