C++20 引入了協程支持,使得編寫異步代碼變得更加簡單。在 C++ 中,協程同步主要通過以下幾種方式實現:
std::future<int> asyncOperation() {
// 異步操作
}
coroutine<int> myCoroutine() {
int result = co_await asyncOperation();
// 處理結果
}
coroutine<int> myCoroutine() {
for (int i = 0; i < 5; ++i) {
co_yield i;
}
}
coroutine<int> myCoroutine() {
int result = 0;
for (int i = 0; i < 5; ++i) {
result += i;
}
co_return result;
}
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread([&]() {
int result = asyncOperation();
prom.set_value(result);
}).detach();
int value = fut.get(); // 獲取異步操作的結果
通過這些方式,C++ 協程可以方便地實現同步操作,使得異步編程更加簡單和直觀。