Golang并发编程Gorutine

前言

什么是Gorutine?

Goroutines are part of making concurrency easy to use.

1.让程序员可以轻松得使用实现大并发效果。

The idea, which has been around for a while, is to multiplex independently executing functions—coroutines—onto a set of threads.

2.Gorutine是建立在线程池之上来实现的

When a coroutine blocks, such as by calling a blocking system call, the run-time automatically moves other coroutines on the same operating system thread

to a different, runnable thread so they won't be blocked.

3.当1个Gorutine遇到IO阻塞时Golang的run-time 会自动得把另一个Gorutine调度到另1个没有被阻塞的线程里面。(永远不会阻塞)

The programmer sees none of this, which is the point. The result, which we call goroutines, can be very cheap: unless they spend a lot of time in long-running system calls, they cost little more than the memory for the stack, which is just a few kilobytes.

5.Gorutin开销非常小,非常轻量级(can be very cheap)大概几千字节。

To make the stacks small, Go's run-time uses segmented stacks. A newly minted goroutine is given a few kilobytes, which is almost always enough.When it isn't, the run-time allocates (and frees) extension segments automatically.

6.为了使Gorutin的stack更小,Golang的runtime使用了segmented stacks(把1个栈划分成一小块一小块的)当Gorutine的栈空间不足时还能自动扩展/缩容。666

The overhead(开销) averages about three cheap instructions per function call. It is practical to create hundreds of thousands of goroutines in the same address space. If goroutines were just threads, system resources would run out at a much smaller number.

7.创建几千个Gorutine也是可行的!

参考

猜你喜欢

转载自www.cnblogs.com/sss4/p/12755374.html