1

I am trying to write a simple C++ application that uses threads and only has to manage a couple of shared variables between the threads. In order to do that simply I decided I would just make these variables std::atomic so I don't have to worry about manually locking and unlocking things.

I tried to start with a simple example where I create an atomic variable in main and pass it to the thread. I was surprised when I attempted to compile it and got a bunch of barely decipherable template related compilation errors.

Passing an atomic by reference:

#include <atomic>
#include <thread>

// Causes an ugly compiler error
void func(std::atomic<int>& i) {
    // Do something that uses "i" in the thread
}

int main() {
    std::atomic<int> i;
    std::thread t(func, i);

    // Do something that uses "i" in main

    t.join();
}

However if I simply pass the atomic variable by pointer it does work.

Passing an atomic by pointer:

#include <atomic>
#include <thread>

// Compiles fine
void func(std::atomic<int>* i) {
    // Do something that uses "i" in the thread
}

int main() {
    std::atomic<int> i;
    std::thread t(func, &i);

    // Do something that uses "i" in main

    t.join();
}

What exactly is happening here? The error (too long to post here, but you can compile it and see) seems to say something about std::atomic not having a copy constructor... but I'm passing it by reference. Why on earth would it be trying to make a copy when passed by reference?

tjwrona1992
  • 8,614
  • 8
  • 35
  • 98
  • `std::thread t(func, i);` you seem to think this conveys that `i` is sent by reference to *that* call, much less eventually conveyed by reference to to the invocation of `func` thereafter by the controlling thread library. Did you try a reference wrapper? `std::thread t(func, std:;ref(i));` – WhozCraig Jul 11 '19 at 16:51
  • Thanks that works :) – tjwrona1992 Jul 11 '19 at 17:19

0 Answers0