Why does this simple c++11 threading-example fail,

2019-02-26 08:41发布

问题:

I can't figure out what I'm doing wrong here. This very short program:

#include <iostream>
#include <string>
#include <atomic>
#include <thread>
using namespace std;

int
main(int argc, char ** argv)
{
        thread foo( []() { 
                cout << "Hello World" << endl;
                return 0; 
        } );
        foo.join();

        return 0;
}

It works perfectly when compiled with gcc (4.7.2):

 $ g++ -ggdb -std=c++11 -pthread -o clang_thread_test clang_thread_test.cpp 
 $ ./clang_thread_test 
Hello World

However, when compiled with clang (3.2; x86_64-pc-linux-gnu; thread model: posix) it fails to execute:

 $ clang++ -ggdb -std=c++11 -pthread -o clang_thread_test clang_thread_test.cpp 
 $ ./clang_thread_test 
pure virtual method called
terminate called without an active exception
Aborted

Is there a known reason for this? The only things I found were related to a missing -pthread switch or a not used libc++. To my knowledge the latter is only relevant on apple-systems.

回答1:

Confirmed that this works:

clang++ --std=c++11 -pthread -D__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 -D__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 -D__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 -D__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53841

chrono thread bug fix for:

linux error: no matching constructor for initialization of 'duration' 

using the Suggested fix:

- const chrono::nanoseconds __delta = __atime - __c_entry;
- const __clock_t::time_point __s_atime = __s_entry
+ __delta; + const auto __delta = __atime - __c_entry;
+ const auto __s_atime = __s_entry
+ __delta; in file condition_variable