Thursday, June 16, 2011

A bit of C++0x std::thread and passing parameters

One small bit from C++0x I want to share with you today is:

you can't use std::thread constructor to pass parameters by reference, all parameters will be passed by value!

Here is a source to demonstrate this:
#include 
#include 

void inc(int& number)
{
    std::cout << "In thread before increment: " << number << std::endl;

    number = number + 1;

    std::cout << "In thread after increment: " << number << std::endl;
}

int main()
{
    int n = 10;

    std::cout << "Before inc: " << n << std::endl;

    std::thread worker(inc, n);
    worker.join();

    std::cout << "After inc: " << n << std::endl;

    return 0;
}
Small note about compiling: I use GNU Compiler Collection (GCC) version 4.5 on Linux (mingw port don't support std::thread yet).
g++ -std=c++0x -lpthread test.cpp -o test
./test
And here is output:
Before inc: 10
In thread before increment: 10
In thread after increment: 11
After inc: 10
UPDATED!!! solution is simple: use the std::ref, Luke!
#include 
#include 

void inc(int& number)
{
    std::cout << "In thread before increment: " << number << std::endl;

    number = number + 1;

    std::cout << "In thread after increment: " << number << std::endl;
}

int main()
{
    int n = 10;

    std::cout << "Before inc: " << n << std::endl;

    std::thread worker(inc, std::ref(n));
    worker.join();

    std::cout << "After inc: " << n << std::endl;

    return 0;
}
and the output is:
Before inc: 10
In thread before increment: 10
In thread after increment: 11
After inc: 11