GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — C++ Library - <coroutine>
Selected Reading
C++ Library - <coroutine>The <coroutine> library in C++20, provides the essential building blocks to use coroutines in C++. Coroutines are the modern feature that allows functions to be paused and resumed at certain points. It provides an efficient mechanism for asynchronous programming, generator functions, and cooperative multitasking, making it easier to work with tasks like networking, file I/O. Unlike traditional functions, coroutines can suspend their execution at certain points and resume later. This is especially useful in scenarios where non-blocking operations(like file I/O or network requests) need to be implemented efficiently. Including <coroutine> HeaderTo include the <coroutine> header in your C++ program, you can use the following syntax. #include <coroutine> Functions of <coroutine> HeaderBelow is list of all functions from <coroutine> header.
Generating a SequenceIn the following example, we are going to create a coroutine that generates a sequence of integers. #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;
}
OutputFollowing is the output of the above code − Next value: 0 Next value: 1 Next value: 2 Next value: 3 Advertisements
| ||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |