Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost thread with c++ 11lambda

How can I use boost thread with C++11 lambda?

The following code doesn't work:

int sum;
m_workerThread=new boost::thread([]()
        {
               for(int i=0;i<100;i++)
               {
                    sum=sum+i;
                }
        }
        );

I am getting compile error.

   Error    4   error C3493: 'sum' cannot be implicitly captured because no default capture mode has been specified 

How can I fix this?

like image 548
mans Avatar asked Jan 09 '23 01:01

mans


1 Answers

As per the error, just need to capture sum. As-is, the lambda doesn't know what sum is:

m_workerThread = new boost::thread([&sum]()
//                                  ^^^^
    {
           for(int i=0;i<100;i++)
           {
                sum=sum+i;
           }
    }
);
like image 194
Barry Avatar answered Jan 12 '23 03:01

Barry