thread pool library

Hi

I am using this thread pool library:

https://github.com/Ethan13310/Thread-Pool-Cpp/tree/master

I am using the following code:

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
#include <thread>
#include <iostream>
#include <chrono>

#include "Thread-Pool/ThreadPool.hpp"

std::mutex mtx;

int main(){

    constexpr std::size_t N = 2;
    thread_pool pool(N);

    auto f = [](int& i)
    {
        std::this_thread::sleep_for (std::chrono::seconds(5));
        mtx.lock();
        i += 4;
        mtx.unlock();
    };

    int i = 0;
    pool.push(f, i);
    pool.push(f, i);
    pool.join();
    std::cout << i;
}


This is outputting 0. Why isn't i increasing in value given I pass it by reference?

Thanks
Probably for the same reason you cannot pass references through the std::thread constructor without using std::ref.

Try:
 
pool.push(f, std::ref(i));
Last edited on
Topic archived. No new replies allowed.