2017-04-26 66 views
2

我正在學習如何使用boost coroutines2庫。我已閱讀了一些教程並開始嘗試使用它。但後來我發現了一些非常混亂的東西。請看這個基本的例子。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. 

當我刪除在協程第二'產率,結果也是相同的:

#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. 

這怎麼可能?它是如何工作的?我期望當我不叫協程時,即使有另一個「收益」在等待,也不會發生任何事情。

而且我覺得也奇怪這種行爲:

當我在主再添「源」的語句,該代碼仍然打印相同,如開頭!

#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(); 
} 

有人能幫助我,請用理解這種行爲?

+0

我也注意到,這與Boost版本有關。我使用wandbox在線編譯器輕鬆選擇boost版本,例如,它可以在Boost 1.59.0上運行FINE。然後在Boost 1.60.0上它也可以正常工作,而在Boost 1.61.0和1.62.0上則停止編譯。然後編譯好,但不適用於Boost 1.63.0。真是一場大屠殺。 – YotKay

+0

和Boost 1.64.0的結果與1.63.0中的結果相同,我的意思是編譯正常,但工作不直觀。或者,也許我在這裏不明白什麼?請幫忙! – YotKay

+0

我不知道他們是否修復了1.63版本中1.59的錯誤或者創建了一個。你怎麼看? – YotKay

回答

相關問題