进程和线程、协程的区别
async 函数的含义和用法
上面两篇文章介绍进程,线程, 和协程,以及javascript中协程的简单用法。
最近在用不用语言开发,分别使用到python, kotlin, javascript 和go,都用到了协程。打算分不同语言写例子记录一下。
javascript
const Coroutine = () => {
return (
<div className="Coroutine">
<Button type="primary" onClick={click_button}>CoroutineTest</Button>
</div>
);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const click_button = async() => {
console.log('Taking a break...');
await sleep(2000);
console.log('Two second later');
}
如上是一个简单的使用async await
实现的javascript 的sleep
方法。
python
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y, result))
return result
if __name__ == '__main__':
loop = asyncio.get_event_loop()
result = loop.run_until_complete(print_sum(1, 2))
loop.close()
print(result)
kotlin:
暂停函数:
suspend fun mySuspendingFun(x: Int) : Result {
…
}
async {
val res = mySuspendingFun(20)
print(res)
}
Android的anko实现库:
async(UI) {
val r1 = bg { fetchResult1() }
val r2 = bg { fetchResult2() }
updateUI(r1.await(), r2.await())
}
网友评论