Exception fliegt in Testprogramm zu std::async
-
Hi,
ich wollte ein kleines Testprogramm schreiben, das mir die ids der Threads anzeigt, die von std::async gespawnt werden (falls sie gespawnt werden).Mein Programm sieht so aus:
#include <iostream> #include <thread> #include <vector> #include <numeric> #include <future> #include <algorithm> // summiere alle Werte in der Range auf int sum(const int * a, const int * b) { std::cout << std::this_thread::get_id() << ' '; auto distance = b-a; if(distance < 5) // willkuerliche Grenze return std::accumulate(a,b,0); const int * half = a + distance/2; auto fut_left = std::async(sum, a, half); auto right = sum(half, b); return fut_left.get() + right; } int main() { std::vector<int> vec(1024); std::iota(vec.begin(), vec.end(), 0); std::cout << sum(vec.data(), vec.data()+1024) << '\n'; }Mit g++ 4.8.1 fliegt eine Exception:
terminate called after throwing an instance of 'std::system_error' what(): Unknown error -1 thread::id of a non-executing thread thread::id of a non-executing thread thread::id of a non-executing thread thread::id of a non-executing thread thread::id of a non-executing thread thread::id of a non-executing thread thread::id of a non-executing thread thread::id of a non-executing thread thread::id of a non-executing thread AbgebrochenHier im online Compiler: http://ideone.com/a8DApC
Sieht jemand, wo ich hier Mist baue?
-
Hast du pthread gelinkt?
-
Du hast recht! Wenn ich pthread linke, dann funktioniert das Programm. Ist es eigentlich standardkonform, pthread linken zu müssen, damit die Standard-Threads funktionieren?
Und leider wird nichts parallel ausgeführt (alle Thread ids sind die gleichen), obwohl mein 4-Kern CPU eine Auslastung von 0% bei Start des Programms hat. Scheinbar traut gcc meinem System nichts zu

-
Ob und was du linken musst ist alles implementationsspezifisch, oder?
-
asdfasd schrieb:
Und leider wird nichts parallel ausgeführt (alle Thread ids sind die gleichen), obwohl mein 4-Kern CPU eine Auslastung von 0% bei Start des Programms hat. Scheinbar traut gcc meinem System nichts zu

Hast du auch mit -pthread übersetzt (nicht nur gelinkt! Wobei -pthread auch ein Linken gegen pthread impliziert)?
-
Was meinst du damit genau?
Ich habe kompiliert mitg++ -O3 -std=c++11 -pthread code.cpp -o outWenn ich die asyncs mit std::launch::async starte, dann erstellt er auch verschiedene Threads. Mit std::launch::async|std::launch::deferred (also dem default) halt nicht. Vielleicht erkennt der Compiler, dass es in dem Fall keinen Sinn hat, separate Threads zu starten? (womit er ja auch recht hätte :D)
-
Laut cppreference,com ist das verhalten normal
If both the std::launch::async and std::launch::deferred flags are set in policy, it is up to the implementation whether to perform asynchronous execution or lazy evaluation.