27
协程Coroutine
source link: https://studygolang.com/articles/20221?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
目录
多任务
-
PHP/Nginx多进程
-
Java多线程
互动: 进程和线程的区别?
协程
-
单线程
-
多任务
互动: 单线程处理多任务类似?
优势
-
单线程 减少多线程操作系统维护成本
-
用户态 减少用户态和内核态切换成本
-
协作式 减少操作系统时间片调度成本
语言
- Python
def consumer(): r = "[C] Consumer start" while True: i = yield r print("[C] Consumer is consuming %s" % i) r = "ok" def producer(consumer): start = consumer.send(None) print(start) for i in range(1, 4): print("[P] Producer is producing %d" % i) r = consumer.send(i) print('[P] Consumer return: %s' % r) consumer.close() if __name__ == "__main__": producer(consumer())
[C] Consumer start [P] Producer is producing 1 [C] Consumer is consuming 1 [P] Consumer return: ok [P] Producer is producing 2 [C] Consumer is consuming 2 [P] Consumer return: ok [P] Producer is producing 3 [C] Consumer is consuming 3 [P] Consumer return: ok
- JavaScript ES6
function timeout(ms) { return new Promise((resolve) => { setTimeout(resolve, ms) }) } async function asyncPrint(value, ms) { await timeout(ms) console.log(value) } asyncPrint("print", 2000) console.log("return")
return print # 2秒后
- Golang
# Todo
更多可以参考 支持协程的编程语言
场景
- IO密集型
互动: 为什么协程适用于IO密集型场景?
参考
-
进程和线程的区别? 线程即共享资源的进程
-
单线程处理多任务类似? IO多路复用
-
为什么协程适用于IO密集型场景? 异步IO
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK