Pass by reference into a threaded function

I'm trying to pass by reference into a threaded function. The values get passed into the function, but I can't send the data out again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <boost/thread.hpp>
#include <Windows.h>
void threadedFunction(int &i)
{
	i++;
	std::cout << "Hello World " << i << std::endl;
}

int main()
{
	int i = 0;

	boost::thread MyThread(threadedFunction, i); //std::thread will also work on some compilers.
	Sleep(1000);
	std::cout << "i became " << i << std::endl;
	return 0;
}
Hello World 1
i became 0


I would have expected the output to say
Hello World 1
i became 1

Is there some other way I can achieve this?

As some background I am trying to pass an STL container into a threaded function. My main function is the entry point to a DLL and is called every 16ms. The container is populated by the main function and then emptied by the threaded function. They emptying takes a while so I don't want to interrupt the main scheduler.
Last edited on
By default, thread's constructor makes copies of its arguments. To pass by reference, use reference_wrapper, which is constructed with std::ref / boost::ref

(also made this portable by sticking to boost where you used windows API)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <boost/thread.hpp>
void threadedFunction(int &i)
{
    i++;
    std::cout << "Hello World " << i << std::endl;
}

int main()
{
    int i = 0;

    boost::thread MyThread(threadedFunction, boost::ref(i));
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    std::cout << "i became " << i << std::endl;
    return 0;
}
Hello World 1
i became 1
This is perfect! I just installed boost today so I haven't figured out how to explore it properly yet. The reference wrapper was exactly what I was looking for and the sleep is good to know about too.

Thanks a ton.
Topic archived. No new replies allowed.