2

我正在学习如何使用 boost coroutines2 库。我已经阅读了一些教程并开始尝试它。但后来我发现了一些非常令人困惑的事情。请看一下这个基本示例。

#include <boost/coroutine2/all.hpp>
#include <iostream>

using namespace std;
typedef boost::coroutines2::coroutine<int> cr;

void creator(cr::push_type& yield)
{
    cout << "First time." << endl;
    yield(1);
    cout << "Second time. " << endl;
    yield(2);
}

int main()
{
    cr::pull_type source{creator};
    source();
}

结果自然是这样的:

First time.
Second time. 

但是,令我惊讶的是,当我删除主函数中的“源”调用时,结果是一样的!(根据教程,协程是在构建时第一次调用,所以调用它是可以的,但现在应该只调用一次!)

#include <boost/coroutine2/all.hpp>
#include <iostream>

using namespace std;
typedef boost::coroutines2::coroutine<int> cr;

void creator(cr::push_type& yield)
{
    cout << "First time." << endl;
    yield(1);
    cout << "Second time. " << endl;
    yield(2);
}

int main()
{
    cr::pull_type source{creator};
}

结果还是:

First time.
Second time. 

当我删除协程中的第二个'yield'时,结果也是一样的:

#include <boost/coroutine2/all.hpp>
#include <iostream>

using namespace std;
typedef boost::coroutines2::coroutine<int> cr;

void creator(cr::push_type& yield)
{
    cout << "First time." << endl;
    yield(1);
    cout << "Second time. " << endl;
}

int main()
{
    cr::pull_type source{creator};
}

结果:

First time.
Second time. 

这怎么可能?它是如何工作的?我预计当我不调用协程时,即使有另一个'yield'等待,也不会发生任何事情。

而且我发现这种行为也很奇怪:

当我在 main 中添加另一个“源”语句时,代码仍然打印与开头相同的内容!

#include <boost/coroutine2/all.hpp>
#include <iostream>

using namespace std;
typedef boost::coroutines2::coroutine<int> cr;

void creator(cr::push_type& yield)
{
    cout << "First time." << endl;
    yield(1);
    cout << "Second time. " << endl;
    yield(2);
}

int main()
{
    cr::pull_type source{creator};
    source();
    source();
}

结果:

First time.
Second time. 

没有错误,即使采购的次数超过了“产量”。只有在主函数中添加了一个“源”后,我才会收到运行时错误(此应用程序已请求运行时以一种不寻常的方式终止它......)

int main()
{
    cr::pull_type source{creator};
    source();
    source();
    source();
}

有人可以帮助我理解这种行为吗?

4

1 回答 1

0

原因在于 Boost 中的一个错误。我在 Boost 1.65.1 中检查过一切正常。这是证明:https ://wandbox.org/permlink/pRuSgnwa3VPdqNUk

于 2017-11-23T16:36:56.273 回答