Go的线程机制和管道
Goroutines(Go的线程机制)
Go允许用go
开启一个新的执行线程–goroutine。它运行在不同的,新创建的的goroutine中。在一个程序中的所有goroutine共享相同的地址空间。
Goroutines是轻量级的,只占用比堆栈分配多一点的空间。堆栈开始小和成长的分配和释放堆(heap)的要求。内部goroutines像进行了复用多个操作系统线程的协程。您不必担心这些细节。
go list.Sort() // Run list.Sort in parallel; don’t wait for it.
Go处理文字的函数,可以作为结束,在处理go
时很强大
func Publish(text string, delay time.Duration) {
go func() {
time.Sleep(delay)
fmt.Println(text)
}() // Note the parentheses. We must call the function.
}
变量text
和delay
在周围函数和函数文字之间共享;只要它们都可以访问,它们就存在。
Channels(管道)
管道通过指定的元素类型的值来提供两个goroutine同步执行和沟通的机制。 <-
操作符指定通道的方向,发送或接收。如无任何指示方向时,通道是双向的。
chan T // can be used to send and receive values of type T
chan<- float64 // can only be used to send float64s
<-chan int // can only be used to receive ints
管道是一个引用类型,用make分配。
ic := make(chan int) // unbuffered channel of ints
wc := make(chan *Work, 10) // buffered channel of pointers to Work
使用<-
作为一个二元操作符来在管道上发送值。当在管道上接收一个值时,把它作为一元运算符。
ic <- 3 // Send 3 on the channel.
work := <-wc // Receive a pointer to Work from the channel.
如果管道是无缓冲,那么发送者阻塞,直到接收器接收到值。如果管道有一个缓冲区,发送者阻塞,直到该值已被复制到缓冲区。如果缓冲区已满,这意味着等待,直到一些接收器中检索到值。接收器被阻塞,直到有数据接收。
并发 (示例)
最后我们用一个例子来说明如何散落的内容拼起来。这是一个服务器通过管道来接受的Work
请求的例子。每个请求都在一个单独的goroutine运行。Work
结构本身包含了一个管道,用于返回一个结果。
package server
import "log"
// New creates a new server that accepts Work requests
// through the req channel.
func New() (req chan<- *Work) {
wc := make(chan *Work)
go serve(wc)
return wc
}
type Work struct {
Op func(int, int) int
A, B int
Reply chan int // Server sends result on this channel.
}
func serve(wc <-chan *Work) {
for w := range wc {
go safelyDo(w)
}
}
func safelyDo(w *Work) {
// Regain control of panicking goroutine to avoid
// killing the other executing goroutines.
defer func() {
if err := recover(); err != nil {
log.Println("work failed:", err)
}
}()
do(w)
}
func do(w *Work) {
w.Reply <- w.Op(w.A, w.B)
}
下面展示如何使用:
package server_test
import (
server "."
"fmt"
)
func main() {
s := server.New()
divideByZero := &server.Work{
Op: func(a, b int) int { return a / b },
A: 100,
B: 0,
Reply: make(chan int),
}
s <- divideByZero
add := &server.Work{
### 文末
如果30岁以前,可以还不知道自己想去做什么的话,那30岁之后,真的觉得时间非常的宝贵,不能再浪费时间在一些碎片化的事情上,比如说看综艺,电视剧。一个人的黄金时间也就二,三十年,不能过得浑浑噩噩。所以花了基本上休息的时间,去不断的完善自己的知识体系,希望可以成为一个领域内的TOP。
同样是干到30岁,普通人写业务代码划水,榜样们深度学习拓宽视野晋升管理。
这也是为什么大家都说30岁是程序员的门槛,很多人迈不过去,其实各行各业都是这样都会有个坎,公司永远都缺的高级人才,只用这样才能在大风大浪过后,依然闪耀不被公司淘汰不被社会淘汰。
**269页《前端大厂面试宝典》**
包含了腾讯、字节跳动、小米、阿里、滴滴、美团、58、拼多多、360、新浪、搜狐等一线互联网公司面试被问到的题目,涵盖了初中级前端技术点。
![](https://img-blog.csdnimg.cn/img_convert/b98713ee557d94286de8afe404cb51d1.png)
**前端面试题汇总**
![](https://img-blog.csdnimg.cn/img_convert/1d691ca297c9016828aff783a701e065.png)
**JavaScript**
![](https://img-blog.csdnimg.cn/img_convert/a489904576da281d07092f043566f6dd.png)