# 协程

## 1. 协程介绍

协程又称微线程，从名字可以看出，协程的粒度比线程更小，并且是用户管理和控制的，多个协程可以运行在一个线程上面。那么协程出现的背景又是什么呢，先来看一下目前线程中影响性能的特性：

* 使用锁机制
* 线程间的上下文切换
* 线程运行和阻塞状态的切换

以上任意一点都是很消耗cpu性能的。相对来说协程是由程序自身控制，没有线程切换的开销，且不需要锁机制，因为在同一个线程中运行，不存在同时写变量冲突，在协程中操作共享资源不加锁，只需要判断状态就行了，所以执行效率比线程高的多。

## 2. 主流语言对协程的支持

**Lua语言**

Lua从5.0版本开始使用协程，通过扩展库coroutine来实现。

**Python语言**

python可以通过 yield/send 的方式实现协程。在python 3.5以后，async/await 成为了更好的替代方案。

**Go语言**

Go语言对协程的实现非常强大而简洁，可以轻松创建成百上千个协程并发执行。

**Java语言**

如上文所说，Java语言并没有对协程的原生支持，但是某些开源框架模拟出了协程的功能，有兴趣的小伙伴可以看一看**Kilim框架**的源码：

<https://github.com/kilim/kilim>

**C/C++**

c/c++需要自己借助ucontext、setjmp、longjmp库实现，微信开源了c/c++的协程库libco。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jun-wang.gitbook.io/learnjava/ji-shu-xue-xi/jia-gou-xue-xi/xie-cheng.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
