Python 在 C/C++ 中的 yield 特性?
python's yield feature in C/C++?
我刚刚了解了python中的yield关键字,这确实非常令人印象深刻和有用。
在C和C++语言中有对等的语言吗?
不是yield
,尽管您可以使用std::iterator
编写惰性迭代器(请参阅此答案)。与Python中的yield
不同,您从operator++
返回下一个元素。
否。
实现yield
需要暂停执行,这不太适合只有一个堆栈(1)的C++模型。实现通用yield
的唯一方法需要在比C++更低的级别上进行(即显式管理堆栈和执行上下文),这在C++级别上是无法实现的。
(1) C++11引入了可移植线程,这意味着可以有多个堆栈,因此可以模拟协同程序(可能效率很低):例如
#include <stdio.h>
#include <thread>
#include <mutex>
template<typename RV>
struct Generator {
std::mutex a, b;
bool done;
RV *current;
Generator() : done(false) {
b.lock();
std::thread([this](){ this->call_run(); }).detach();
}
void call_run() {
this->run();
done = true;
}
virtual void run() = 0;
void yield(const RV & x) {
a.lock();
*current = x;
b.unlock();
}
bool next(RV & res) {
if (done) return false;
current = &res;
a.unlock();
b.lock();
return true;
}
};
///////////////////////////////////////////////////////
struct Squares : Generator<int> {
void run() override {
for (int i=0; i<10; i++) {
yield(i*i);
}
}
};
int main() {
Squares sq;
int x = -1;
while(sq.next(x)) {
printf("%in", x);
}
return 0;
}
相关文章:
- 如果我们使用 notify_one() 来唤醒线程,我们还需要 yield() - C++?
- 当工件是库并且标志影响C或C++头时,特性标志/切换
- C++:编译对无关派生类、bug或特性的函数调用
- 设置窗口几何图形特性的正确方法
- 对于非常大的输入,缺少和重复 1..n 的数字数组.使用1..n系列特性的解决方案.溢出问题
- 如果我对"while"块发表评论,为什么程序会死机?其中的"yield"线有何影响?
- Movesense设备中的真实自定义Gatt服务和特性
- 如何:非根QML前端和根特性的工作人员线程
- 无向DFS:如何提供颜色图作为外部特性
- 我如何让GDB告诉我记忆特性一个给定的地址
- c++11新特性,正确使用shared_ptr
- 运行时特性测试、setjmp、longjmp和信号掩码
- Qt 和 Android 特性更改不发出
- wxWidgets 3.0-新特性和功能,添加和替换不推荐使用的特性和功能
- g++(4.7.2)错误或特性,在编译时初始化静态数组时
- 获取表面浅色特性
- 除了移动语义,还有哪些C++11特性可以提高代码的性能
- 请解释一个特性单例(C++)
- 如果延迟很重要,我应该在繁忙循环中使用std::this_thread::yield吗
- Python 在 C/C++ 中的 yield 特性?