用于 c++0x 原子和线程的 GCC 标志

GCC flags for c++0x atomics and threads

本文关键字:GCC 标志 线程 c++0x 用于      更新时间:2023-10-16

我试图编译这个C++原子和线程的基本示例,尽管当我编译主文件时.cpp gcc会抛出一些std lib错误 - 这似乎与我的代码无关。

主.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: %sn", flag.is_lock_free() ? "true" : "false");
for (;;) {
sharedValue = 0;
thread thread2(Thread2Func);
IncrementSharedValue10000000Times(randomDelay1);
thread2.join();
printf("sharedValue=%dn", 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

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

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

>你需要添加包含你的RandomDelay定义的cpp文件..ie类似于g++ -std=c++0x -pthread main.cpp randomdelay.cpp