2017-12-08 4 views
0

Ich habe den std versucht: Asynchron-Codebeispiel hier http://www.cplusplus.com/reference/future/async/C++ std :: async trifft auf system_error?

Aber ich Systemfehler mit unbekannten Fehlern auftreten -1. Kann mir jemand helfen? Vielen Dank!

Es folgt mein Code, der von der Website kopiert wird:

// async example 
#include <iostream>  // std::cout 
#include <future>   // std::async, std::future 

// a non-optimized way of checking for prime numbers: 
bool is_prime (int x) { 
    std::cout << "Calculating. Please, wait...\n"; 
    for (int i=2; i<x; ++i) if (x%i==0) return false; 
    return true; 
} 

int main() 
{ 
    // call is_prime(313222313) asynchronously: 
    std::future<bool> fut = std::async (is_prime,313222313); 

    std::cout << "Checking whether 313222313 is prime.\n"; 
    // ... 

    bool ret = fut.get();  // waits for is_prime to return 

    if (ret) std::cout << "It is prime!\n"; 
    else std::cout << "It is not prime.\n"; 

    return 0; 
} 

Und die folgende ist meine Kommandozeile:

ubuntu:~/cpp_dynamic_invoke_success/stdasync_test$ g++ isprime.cpp -std=c++11 -o isprime 
ubuntu:~/cpp_dynamic_invoke_success/stdasync_test$ ./isprime 
Checking whether 313222313 is prime. 
terminate called after throwing an instance of 'std::system_error' 
    what(): Unknown error -1 
Aborted (core dumped) 

Meine ubuntu Version:

No LSB modules are available. 
Distributor ID: Ubuntu 
Description: Ubuntu 14.04.3 LTS 
Release: 14.04 
Codename: trusty 

Und g ++ Version .

g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 
Copyright (C) 2013 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
+0

Obwohl es keine Antwort hat, ist dies ein Narr [diese Frage] (https://stackoverflow.com/questions/46634629/c-async-sometimes-resulting-in-stdsystem-error -und-manchmal-nicht) – bnaecker

+1

Dies ist eine ziemlich alte Version von GCC, daher müssen Sie möglicherweise am Ende Ihres Kompilierungsbefehls das Flag '-pthread' hinzufügen. – bnaecker

+0

Danke! add-'thread' ist wirklich hilfreich! – desword

Antwort

0

Die Antwort ist hinzuzufügen -pthread aftet die Kompilierungsoption.

g++ isprime.cpp -std=c++11 -o isprime -pthread 
Verwandte Themen