Pass variable to thread as reference (C++14)

I want pass variable of custom type to thread creation. And I want pass it as reference. But this code does not work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <mutex>
#include <vector>
#include <thread>
#include <condition_variable>

using namespace std;

class ChannelTest {
private:
    size_t capacity;
public:
    ChannelTest(size_t c) : capacity(c) {}
};

void searchRoutineTest(ChannelTest &ch, const int &num) { // <<<===== HERE!
    cout << "Test: " << num << endl;
}

int main(int argc, char **argv) {
    std::vector<std::thread> ts;
    ChannelTest channel(4);

    for (int i = 0; i < 20; ++i) {
        ts.emplace_back(&searchRoutineTest, channel, i);
    }

    for (std::thread &t : ts) {
        t.join();
    }

    return 0;
}



Sample here http://cpp.sh/9t7ul


And if I change marked row with "const ChannelTest &ch" patch, it will works.
Why I can't use reference without const modificator??
What if I want change channel var in threads?
> Why I can't use reference without const modificator??

The argument to the thread function is copied (it is passed by value).
To pass an argument by reference to the thread function, it must be wrapped.

ts.emplace_back( &searchRoutineTest, std::ref(channel), i )


> What if I want change channel var in threads?

You need to avoid race conditions. For example, with:
1
2
3
4
5
6
7
8
9
10
class ChannelTest {

    private:
        std::atomic<std::size_t> capacity;

    public:
        ChannelTest( std::size_t c ) : capacity(c) {}

        void modify_it() { ++capacity ; } // atomic; ergo thread safe
};
> You need to avoid race conditions. For example, with:

Oh, I just ask how I can work with channel if it will be const. I remove mutex and another field for demo.

> ts.emplace_back( &searchRoutineTest, std::ref(channel), i )

And how this problem solved before C++11?
I tryed to write smt like this:

1
2
ChannelTest channel(4);
ChannelTest &ref = channel;


but catch same error. What's wrong?
> And how this problem solved before C++11?

Before C++11, the language was not thread aware. One used platform specific thread support provided by a C API; C supports only pass by value semantics (typically, these thread APIs accepted pointers).


> but catch same error. What's wrong?

Repeat:
The argument to the thread function is copied (it is passed by value).
To pass an argument by reference to the thread function, it must be wrapped.

The library provided wrapper is std::reference_wrapper<> https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
Topic archived. No new replies allowed.