C ++ 0x原子和线程的GCC标志

时间:2012-10-19 19:34:40

标签: c++ c++11 pthreads atomic-swap

我试图编译这个C ++原子的基本例子&但是当我编译main.cpp文件时,gcc会抛出一些std lib错误 - 这似乎与我的代码无关。

的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

这里是gcc错误消息:

[lewis@localhost 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

2 个答案:

答案 0 :(得分:2)

RandomDelay类似乎在randomdelay.cpp中实现。您必须编译此文件并将其与main.cpp链接在一起。例如:

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

答案 1 :(得分:2)

你需要添加包含RandomDelay定义的cpp文件,例如g++ -std=c++0x -pthread main.cpp randomdelay.cpp