LightKeep
LightKeep

Reputation: 33

c++ std::thread problems in Visual Studio 2012

I'm trying to execute this code.

BOOL genFunctionOne(std::vector <char> functionOneBuffer, int functionOneCharCount)
{
  int lineCountTest = 0;
  int characterCountTest = 0;

  for (int i = 0; i < functionOneCharCount; i++)
  {
    if (functionOneBuffer[i] == '\n')
      lineCountTest++;

    characterCountTest++;
  }

  return FALSE;     
}

With this call.

std::thread funcThreadOne( [&] { functionOne = genFunctionOne( functionBufferOne, functionCharCountOne ); } );

And everytime I call the function. I get..

Microsoft Visual C++ Runtime Library

Debug Error!

Program:... my.exe

R6010
-abort() has been called

Please retry to debug the application.

The Break Point is cause by... crt0msg.c

            if (rterrnum != _RT_CRNL && rterrnum != _RT_BANNER && rterrnum != _RT_CRT_NOTINIT)
        {
            switch (_CrtDbgReportW(_CRT_ERROR, NULL, 0, NULL, L"%s", error_text))
            {
            case 1: _CrtDbgBreak(); msgshown = 1; break;
            case 0: msgshown = 1; break;

Thanks in advance.

I have actually tried to run other thread calls in the same program and have had no luck. It could be my compiler, are there any libraries that need to be linked in build options with #include ?

Upvotes: 3

Views: 7154

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283634

Please note that lambdas usually are used only inside the complete-expression where they appear, and that the temporary lambda object will be destroyed at the end of that complete-expression.

I would expect std::thread to make a copy of the functor object passed in, to avoid lifetime problems.

But you can ensure there's no issue via:

auto threadProc =  [&] { functionOne = genFunctionOne( functionBufferOne, functionCharCountOne ); };
std::thread funcThreadOne(threadProc);
funcThreadOne.join(); // <- make sure you do this before threadProc goes out of scope

(Note: the Standard does require std::thread to make a copy of the functor and all arguments, and also requires a lambda object to have a copy-constructor. But Visual C++ may not meet these requirements yet.)

Upvotes: 0

cooky451
cooky451

Reputation: 3510

Do you join or detach the thread before exiting scope? Because you have to. Exiting scope with a thread running calls terminate.

Upvotes: 13

Related Questions