社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
Goroutines are part of making concurrency easy to use. The idea, which has been around for a while, is to multiplex independently executing functions—coroutines—onto a set of threads. 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. 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.
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. 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.
goroutine_list = [A, B, C]
while(goroutine):
for goroutine in goroutine_list:
r = goroutine()
if r.finished():
goroutine_list.remove(r)
def A:
上次跑到的地方 = 找到上次跑哪儿了
读取所有临时变量
goto 上次跑到的地方
a = 1
print("do something")
go.scheduler.保存程序指针 // 设置"这次跑哪儿了"
go.scheduler.保存临时变量们
go.scheduler.跑够了_换人 //相当于return
print("do something again")
print(a)
string s = go.file.readFile("/root")
// 实际上
handler h = someOS.asyncReadFile("/root") //很快返回一个handler
while (!h.finishedAsyncReadFile()): //很快返回Y/N
go.scheduler.保存现状()
go.scheduler.跑够了_换人() // 相当于return,不过下次会从这里的下一句开始执行
string s = h.getResultFromAsyncRead()
def A:
print("do something")
go.os.InvokeSomeReallyHeavyAndBlockingSystemCall()
print("do something 2")
def 真实的A:
print("do something")
Thread t = new Thread( () => {
SomeReallyHeavyAndBlockingSystemCall();
})
t.start()
while !t.finished():
go.scheduler.保存现状
go.scheduler.跑够了_换人
print("finished")
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!