go为什么适合高并发
1.go调度器:GMP方式,goruntine阻塞时OS Thread会启用其他goruntine去执行,而不是像传统的多线程阻塞OSThread。
2.利用channel进行通信时,可以直接在goruntine之间拷贝数据,不一定会拷贝到chan的方式。协程A读取空的chan,会gopark自己,然后加入hchan的rece队列,等待被唤醒。当协程B向chan中送数据,发现等待队列有sudog,则会直接将数据拷贝到协程A的栈中。
channel 原理:
1.go语言中有句话叫做“通过通信来共享内存而不是通过共享内存来通信”,其中就用到了channel进行完成。
2.channel原理中主要用到了hchan这个结构体,在hcahn中的字段有
,其中buf规定channel缓存区的大小,他是个循环数组。sendx,recvx代表当前发送和接收的下标位置。sendq和recvq是两个链表形式的组成
可知链表是双向链表,每个链表中都是sudog结构体,这些sudog就是抽象的goroutine。
向chan发送数据源码:
func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {
if c == nil {
if !block {
return false
}
gopark(nil, nil, waitReasonChanSendNilChan, traceEvGoStop, 2)
throw("unreachable")
}
if debugChan {
print("chansend: chan=", c, "\n")
}
if raceenabled {
racereadpc(c.raceaddr(), callerpc, funcPC(chansend))
}
// Fast path: check for failed non-blocking operation without acquiring the lock.
//
// After observing that the channel is not closed, we observe that the channel is
// not ready for sending. Each of these observations is a single word-sized read
// (first c.closed and second full()).
// Because a closed channel cannot transition from 'ready for sending' to
// 'not ready for sending', even if the channel is closed between the two observations,
// they imply a moment between the two when the channel was both not yet closed
// and not ready for sending. We behave as if we observed the channel at that moment,
// and report that the send cannot proceed.
//
// It is okay if the reads are reordered here: if we observe that the channel is not
// ready for sending and then observe that it is not closed, that implies that the
// channel wasn't closed during the first observation. However, nothing here
// guarantees forward progress. We rely on the side effects of lock release in
// chanrecv() and closechan() to update this thread's view of c.closed and full().
if !block && c.closed == 0 && full(c) {
return false
}
var t0 int64
if blockprofilerate > 0 {
t0 = cputicks()
}
lock(&c.lock)
if c.closed != 0 {
unlock(&c.lock)
panic(plainError("send on closed channel"))
}
if sg := c.recvq.dequeue(); sg != nil {
// Found a waiting receiver. We pass the value we want to send
// directly to the receiver, bypassing the channel buffer (if any).
send(c, sg, ep, func() { unlock(&c.lock) }, 3)
return true
}
if c.qcount < c.dataqsiz {
// Space is available in the channel buffer. Enqueue the element to send.
qp := chanbuf(c, c.sendx)
if raceenabled {
racenotify(c, c.sendx, nil)
}
typedmemmove(c.elemtype, qp, ep)
c.sendx++
if c.sendx == c.dataqsiz {
c.sendx = 0
}
c.qcount++
unlock(&c.lock)
return true
}
if !block {
unlock(&c.lock)
return false
}
// Block on the channel. Some receiver will complete our operation for us.
gp := getg()
mysg := acquireSudog()
mysg.releasetime = 0
if t0 != 0 {
mysg.releasetime = -1
}
// No stack splits between assigning elem and enqueuing mysg
// on gp.waiting where copystack can find it.
mysg.elem = ep
mysg.waitlink = nil
mysg.g = gp
mysg.isSelect = false
mysg.c = c
gp.waiting = mysg
gp.param = nil
c.sendq.enqueue(mysg)
// Signal to anyone trying to shrink our stack that we're about
// to park on a channel. The window between when this G's status
// changes and when we set gp.activeStackChans is not safe for
// stack shrinking.
atomic.Store8(&gp.parkingOnChan, 1)
gopark(chanparkcommit, unsafe.Pointer(&c.lock), waitReasonChanSend, traceEvGoBlockSend, 2)
// Ensure the value being sent is kept alive until the
// receiver copies it out. The sudog has a pointer to the
// stack object, but sudogs aren't considered as roots of the
// stack tracer.
KeepAlive(ep)
// someone woke us up.
if mysg != gp.waiting {
throw("G waiting list is corrupted")
}
gp.waiting = nil
gp.activeStackChans = false
closed := !mysg.success
gp.param = nil
if mysg.releasetime > 0 {
blockevent(mysg.releasetime-t0, 2)
}
mysg.c = nil
releaseSudog(mysg)
if closed {
if c.closed == 0 {
throw("chansend: spurious wakeup")
}
panic(plainError("send on closed channel"))
}
return true
}
可知:
1.向nil的chan里发送数据,取决于block是否是true,如果是select里包围的chan,block = false 而如果是普通的chan,block = true 。如果是true,则会协程自己调用gopark()阻塞并且返回异常信息(unreachable),如果是false,则直接返回false,false 为0。
2.向nil的chan里接收数据,流程同上。
3.如果chan为close,产生panic,返回0
然后判断recvq是否有等待着的协程,如果有,则直接将数据拷贝到该协程中并且goready(该协程)
4.向close的chan接收同上,返回0
5.向空的chan接收数据会阻塞,并且将goroutine抽象为sudog结构体加入到recvq中
6.向满的chan发送数据会阻塞,并且将goroutine抽象为sudog结构体加入到sendq中