vendredi 21 octobre 2016

Difference in C++11 async behaviour on Mac and Linux

Consider the following C+11 code:

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

using namespace std;

int main() {
    auto start = chrono::steady_clock::now();
    auto elapsed = [start](string s) {
        cout << s << (chrono::steady_clock::now() - start).count() << endl;
    };

    elapsed("A ");
    auto fut (async([]() { this_thread::sleep_for(chrono::seconds(2)); }));
    elapsed("B ");
    this_thread::sleep_for(chrono::seconds(1));
    elapsed("C ");
    fut.wait();
    elapsed("D ");
    return 0;
}

Mac Results

Compiling said code on macOS Sierra with the command c++ -std=c++11 -stdlib=libc++ -Wall question.cc -o question and running, I get the output:

A 27186
B 86970
C 1001961755
D 2001585903

which is expected. It took minimal time to get to A and B, waited 1 second and then got to C, and waiting the remaining of the 2 seconds (1 already elapsed) to get to D.

The Mac compiler is:

$ c++ --version
Apple LLVM version 8.0.0 (clang-800.0.38)
Target: x86_64-apple-darwin16.0.0
Thread model: posix

Linux Results

On Linux, I compiled the same code with c++ -std=c++11 -pthread question.cc -o question and ran, and got the result:

A 32423
B 444340
C 1003635793
D 3006121895

The Linux compiler is:

$ c++ --version
c++ (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.

Q

Why is there the fully 2 second lag between C and D on Linux? Wasn't the async task supposed to run in the background? Am I using the wrong compile options?

Aucun commentaire:

Enregistrer un commentaire