Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread function with passed by reference vector is slow to start

I've been looking at C++0x threads and have this code:

#include <vector>
#include <iostream>
#include <thread>
void TestFunc(const vector<int>& vVec)
{
    cout << "in"<<endl;
}

int main()
{

    int sizer = 400000000;

    vector<int> vTest(sizer);
    for(int f=0; f<sizer; f++)
        vTest[f] = f;


   cout << "V created." << endl;

   thread one(TestFunc, vTest);

     one.join();    

}

As you can see it just passes a vector to a thread. The thing I don't understand is that there is a pause after the message "V created" appears. Originally this (I assumed) was the vector being copied for use in the function. To stop this I passed by reference instead but this made no difference.

The delay seems to be proportional to the size of the vector which indicates that it is still copying (or doing something with the array). If I try the same experiment without threads and just call the function directly the delay is there when passing by value but not when passing by reference as I expected.

I tried the same using Boost threads instead of C++0x (even though I've read that they are much the same) and got the same result.

Is there some reason for this behaviour or have I missed something blindingly obvious? Thanks.

Sorry, posted the wrong test code. Corrected. Edit: Added includes as requested.

Compiled with: g++44 -std=c++0x -lpthread tester.cpp -o test ...as I have GNU 4.4 installed along side the standard GNU compiler that comes with my Linux (CentOS) which doesn't support C++11.

like image 534
Columbo Avatar asked Nov 28 '11 11:11

Columbo


1 Answers

I'm just speculating, since you haven't posted the version of the code that uses threads, but I would suspect your problem is that, by default, std::bind (or boost::bind) make copies of all the arguments you bind. To avoid this, you can use std::ref or std::cref.

To make this concrete, you're probably using bind like this:

std::bind(TestFunc, vTest)

Instead, you should use it like this:

std::bind(TestFunc, std::cref(vTest));
like image 168
Martin B Avatar answered Oct 30 '22 04:10

Martin B