2016-12-16 16 views
6
#include <iostream> 
#include <string> 
#include <thread> 
#include <future> 


int main() 
{ 
    auto pms = std::promise<std::string>(); 
    auto ftr = pms.get_future(); 

    std::thread([&](){pms.set_value("hello world");});  
    ftr.wait(); 
    std::cout << ftr.get() << std::endl; 

    return 0; 
} 

, std::future::wait blok sonuç avaiable hale gelene kadar. Ancak, yukarıdaki kod hiçbir şey yazdıramıyor. Açıkça, ana iplik, pms.set_value'un ipliğinin bitmesinden önce bitti.
Neden gelecekteki :: bekleme() bloke etmez

Neden ftr.wait() engellemiyor?

+0

std bir göz atmanızı öneririm :: – LeDYoM

cevap

9

Sorun, std::future::wait'un engellenmesi değil. Asıl sorun, ürettiğiniz iş parçacığı arasında bir yarış durumunuz olması, işini yapması ve ana iş parçacığında std::thread (geçici) nesnesinin yok olmasıdır.

Bu nedenle, std::thread yıkıcıda iş parçacığı hala birleştirilebilirse, abort yok denir.

Çalışma kodu: Açıkça thread katılmak etmemeleri durumunda main daha hızlı çalışmalarını yapabileceği olası beri

#include <iostream> 
#include <string> 
#include <thread> 
#include <future> 
#include <chrono> 

int main() 
{ 
    auto pms = std::promise<std::string>(); 
    auto ftr = pms.get_future(); 

    std::thread thread ([&](){pms.set_value("hello world");});  
    ftr.wait(); 
    std::cout << ftr.get() << std::endl; 
    thread.join(); 
    return 0; 
} 

Not, hala daha thread can, (aynı yarış durumu olurdu yukarı kendisini temizlemek

çalışma örnek

Demo:.. here

+3

Upvoted zaman uyumsuz iş parçacığı ayrılması önermiyorum için. –

0

Alternatif iplik ayırmak veyerine promise::set_value_at_thread_exit kullanmak

#include <iostream> 
#include <string> 
#include <thread> 
#include <future> 
#include <chrono> 


int main() 
{ 
    auto pms = std::promise<std::string>(); 
    auto ftr = pms.get_future(); 

    std::thread([&](){pms.set_value_at_thread_exit("hello world");}).detach();  
    ftr.wait(); 
    std::cout << ftr.get() << std::endl; 

    return 0; 
} 
İlgili konular