2012-10-19 19 views
-1

我試圖編譯C++原子的基本示例&線程雖然當我編譯main.cpp文件gcc拋出一些std lib錯誤 - 這似乎無關我的代碼。GCC標誌爲C++ 0x原子和線程

的main.cpp

#include <thread> 
#include <atomic> 
#include <stdio.h> 
#include "randomdelay.h" 

using namespace std; 

atomic<int> flag; 
int sharedValue = 0; 

RandomDelay randomDelay1(1, 60101); 
RandomDelay randomDelay2(2, 65535); 

void IncrementSharedValue10000000Times(RandomDelay& randomDelay) 
{ 
    int count = 0; 
    while (count < 10000000) 
    { 
     randomDelay.doBusyWork(); 
     int expected = 0; 
     if (flag.compare_exchange_strong(expected, 1, memory_order_relaxed)) 
     { 
      // Lock was successful 
      sharedValue++; 
      flag.store(0, memory_order_relaxed); 
      count++; 
     } 
    } 
} 

void Thread2Func() 
{ 
    IncrementSharedValue10000000Times(randomDelay2); 
} 

int main(int argc, char* argv[]) 
{ 
    printf("is_lock_free: %s\n", flag.is_lock_free() ? "true" : "false"); 

    for (;;) { 
     sharedValue = 0; 
     thread thread2(Thread2Func); 
     IncrementSharedValue10000000Times(randomDelay1); 
     thread2.join(); 
     printf("sharedValue=%d\n", sharedValue); 
    } 

    return 0; 
} 

我使用的是全碼:https://github.com/preshing/AcquireRelease

這裏的海灣合作委員會的錯誤消息:

[[email protected] preshing-AcquireRelease-1422872]$ g++ -std=c++0x -pthread main.cpp 
/tmp/cc95LElq.o: In function `IncrementSharedValue10000000Times(RandomDelay&)': 
main.cpp:(.text+0xdd): undefined reference to `RandomDelay::doBusyWork()' 
/tmp/cc95LElq.o: In function `__static_initialization_and_destruction_0(int, int)': 
main.cpp:(.text+0x23d): undefined reference to `RandomDelay::RandomDelay(int, int)' 
main.cpp:(.text+0x251): undefined reference to `RandomDelay::RandomDelay(int, int)' 
collect2: error: ld returned 1 exit status 

下面是我用命令:g++ -std=c++0x -pthread main.cpp

+1

如何在這些不相關的代碼?未定義對'RandomDelay'中所有函數的引用。 – GManNickG

+0

@GManNickG我指的是GCC標誌。 – TheBlueCat

+1

是什麼導致你設置這個關於原子和GCC標誌的問題? –

回答

1

RandomDelay類似乎是我在randomdelay.cpp補充。您必須編譯此文件並將其與main.cpp鏈接在一起。例如:

$ g++ -std=c++0x -pthread -o program_name main.cpp randomdelay.cpp 
+0

+1。謝謝;我沒有意識到這並不容易。 – TheBlueCat

+0

不幸的是我的CPU確實輸出了所需的輸出,正如我所料。 – TheBlueCat

1

,你需要在你的CPP文件,其中包含添加RandomDelay defintiion ..即像g++ -std=c++0x -pthread main.cpp randomdelay.cpp