I have tried to compile this basic example of C++ atomics & threads though when I got to compile the main.cpp file gcc throws up a few std lib errors - which seem unrelated to my code.
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;
}
Full code I'm using: https://github.com/preshing/AcquireRelease
here's the gcc error messages:
[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
Here's the command I use: g++ -std=c++0x -pthread main.cpp
The RandomDelay
class seems to be implemented in randomdelay.cpp
. You have to compile this file and to link it together with main.cpp
. For instance:
$ g++ -std=c++0x -pthread -o program_name main.cpp randomdelay.cpp