【练习】goroutine chan 通道 总结
2024-10-21 09:44:10
1、
fatal error: all goroutines are asleep - deadlock!
所有的协程都休眠了 - 死锁!
package main
import("fmt")
func f1(in chan int){
fmt.Println(<-in)
}
func main(){
out :=make(chan int)
out<-2
go f1(out)
}
package main
import("fmt")
func f1(in chan int){
fmt.Println(<-in)
}
func main(){
out :=make(chan int)
// out<-2
go f1(out)
out<-2
}
Understanding the context package in golang - Parikshit Agnihotry http://p.agnihotry.com/post/understanding_the_context_package_in_golang/
package main import "fmt" //prints to stdout and puts an int on channel
func printHello(ch chan int) {
fmt.Println("Hello from printHello")
//send a value on channel
ch <- 2
} func main() {
//make a channel. You need to use the make function to create channels.
//channels can also be buffered where you can specify size. eg: ch := make(chan int, 2)
//that is out of the scope of this post.
ch := make(chan int)
//inline goroutine. Define a function and then call it.
//write on a channel when done
go func(){
fmt.Println("Hello inline")
//send a value on channel
ch <- 1
}()
//call a function as goroutine
go printHello(ch)
fmt.Println("Hello from main") //get first value from channel.
//and assign to a variable to use this value later
//here that is to print it
i := <- ch
fmt.Println("Recieved ",i)
//get the second value from channel
//do not assign it to a variable because we dont want to use that
<- ch
}
Hello from main
Hello from printHello
Recieved 2
Hello inline
golang channel 使用总结 - litang.me http://litang.me/post/golang-channel/
- http://www.usingcsp.com/
- https://go101.org/article/channel.html
- https://go101.org/article/channel-use-cases.html
- https://go101.org/article/channel-closing.html
- https://www.jianshu.com/p/819aa9b9af86
package main
import (
"fmt"
"time"
)
func fA(ch chan bool) {
defer func() {
fmt.Println("fA-defer")
}()
fmt.Println("fA-doing")
ch <- true
time.Sleep(time.Duration(123) * time.Millisecond)
}
func fB(ch chan bool) {
defer func() {
fmt.Println("fB-defer")
}()
fmt.Println("fB-doing")
ch <- true
}
func main() {
defer func() {
fmt.Println("main-defer")
}()
ch := make(chan bool)
go fA(ch)
go fB(ch)
<-ch
<-ch
}
目前打印结果为:
fB-doing
fB-defer
fA-doing
main-defer
修改代码打印结果为:
fB-doing
fB-defer
fA-doing
fA-defer
main-defer
交换
ch <- true
time.Sleep(time.Duration(123) * time.Millisecond)
位置
最新文章
- [POJ3111]K Best(分数规划, 二分)
- go语言常用函数:copy
- [转]REST简介
- linux查看rpm包创建的所有目录和文件
- 从Java的角度理解前端框架,nodejs,reactjs,angularjs,requirejs,seajs
- C#基础练习(使用委托窗体传值)
- 微软数学库XNAMATH(DirectXMath)
- 未来 USB Type-C 将可靠软体判断线材是否符合规定
- 【转】【Android UI设计与开发】第07期:底部菜单栏(二)Fragment的详细介绍和使用方法
- windows服务-log4net的使用
- ssl证书验证
- SLAM+语音机器人DIY系列:(二)ROS入门——3.在ubuntu16.04中安装ROS kinetic
- 【RL-TCPnet网络教程】第20章 RL-TCPnet之BSD Socket客户端
- NPOI 的使用姿势
- 用Python自动发送邮件
- python模块之HTMLParser抓页面上的所有URL链接
- ffmpeg 播放音频
- 使用手机预览移动端项目(Vue)
- codevs 1214 线段覆盖
- 记录memcache分布式策略及算法