C++ 庫 - <coroutine>



C++20 中的<coroutine> 庫提供了使用協程的基本構建塊。協程是允許函式在某些點暫停和恢復的現代特性。它提供了一種有效的非同步程式設計、生成器函式和協作多工處理機制,從而更容易處理網路、檔案 I/O 等任務。

與傳統函式不同,協程可以在某些點暫停其執行並在以後恢復。這在需要有效實現非阻塞操作(如檔案 I/O 或網路請求)的場景中特別有用。

包含 <coroutine> 標頭檔案

要在 C++ 程式中包含 <coroutine> 標頭檔案,可以使用以下語法。

#include <coroutine>

<coroutine> 標頭檔案的功能

以下是 <coroutine> 標頭檔案中所有函式的列表。

序號 函式和描述
1 operator=

它賦值 coroutine_handle 物件。

2 operator coroutine_handle<>

它獲取一個型別擦除的 coroutine_handle。

3 done

它檢查協程是否已完成。

4 operator bool

它檢查控制代碼是否代表一個協程。

5 operator() & resume

它恢復協程的執行。

6 destroy

它銷燬一個協程。

7 promise

它訪問協程的 promise。

8 address

它匯出底層地址。

生成序列

在下面的示例中,我們將建立一個生成整數序列的協程。

#include <iostream>
#include <coroutine>
struct x {
   struct promise_type {
      int a;
      int b = 0;
      x get_return_object() {
         return x {
            this
         };
      }
      std::suspend_always initial_suspend() {
         return {};
      }
      std::suspend_always final_suspend() noexcept {
         return {};
      }
      void return_void() {}
      void unhandled_exception() {}
      std::suspend_always yield_value(int val) {
         a = val;
         return {};
      }
      int getNext() {
         return b++;
      }
   };
   promise_type * promise;
   x(promise_type * p): promise(p) {}
   int next() {
      promise -> yield_value(promise -> getNext());
      return promise -> a;
   }
};
x generateSequence() {
   for (int i = 0; i < 4; ++i) {
      co_yield i;
   }
}
int main() {
   auto sequence = generateSequence();
   for (int i = 0; i < 4; ++i) {
      std::cout << "Next value: " << sequence.next() << '\n';
   }
   return 0;
}

輸出

以下是上述程式碼的輸出:

Next value: 0
Next value: 1
Next value: 2
Next value: 3
廣告