2013-12-15 41 views
0

這是我的代碼。gcc中C++ 11線程的奇怪行爲4.8.1

#include <thread> 
#include <iostream> 
//#include <ctime> 

using namespace std; 

void f() {} 

int main() { 
    //struct timespec t; 
    //clock_gettime(CLOCK_REALTIME, &t); 
    thread(f).join(); 
    return 0; 
} 

我曾嘗試通過以下方式來編譯這個程序:

1. g++ a.cc -o a -std=c++11 -pthread 
2. g++ a.cc -o a -std=c++11 -lpthread 
3. g++ -pthread a.cc -o a -std=c++11 
4. g++ a.cc -c -std=c++11 && g++ a.o -o a -lpthread 
5. g++ a.cc -c -std=c++11 -pthread && g++ a.o -o a -pthread 

他們都可以輸出可執行的「a」。然而,他們都不到圖書館鏈接「libpthread.so」:

./a 
terminate called after throwing an instance of 'std::system_error' 
    what(): Enable multithreading to use std::thread: Operation not permitted 
Aborted 

ldd ./a 
linux-vdso.so.1 => (0x00007fff997fe000) 
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f350f7b5000) 
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f350f59f000) 
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f350f1d6000) 
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f350eed2000) 
/lib64/ld-linux-x86-64.so.2 (0x00007f350fad4000) 

但是,下面的方式完美的作品:

  1. 取消註釋所有三個在上面的代碼行(必須做這個,或者出現同樣的錯誤);

  2. 使用「g ++ a.cc -std = C++ 11 -o a -lrt」。

我使用的是Ubuntu 13.10。有什麼理由呢?

+0

如果用編譯'G ++ - 4.8 -std = C++ 11 -Wall a.cc -lpthread -oa'(在Debian /希德使用GCC 4.8.2),你的程序工作正常(和不顯式的'-lpthread'我得到相同的錯誤,你會得到)。 –

回答

1

This would seem to be a known Ubuntu related bug

您可以(如鏈接頁面所述)通過在命令行上傳遞-Wl,--no-as-needed來解決該問題;

> g++ a.cc -pthread -std=c++11 
> ./a.out 
terminate called after throwing an instance of 'std::system_error' 
    what(): Enable multithreading to use std::thread: Operation not permitted 
> 

> g++ a.cc -pthread -std=c++11 -Wl,--no-as-needed 
> ./a.out 
>