Mikhail
Mikhail

Reputation: 8028

Boost::threads work in debug, don't in release

I started doing threads about an hour ago and am having some trouble where the debug mode does what I expect and the release mode cashes.

Debug

g++ -c -g -MMD -MP -MF build/Debug/GNU-Linux-x86/foo.o.d -o build/Debug/GNU-Linux-x86/foo.o foo.cpp

Whatever 2222222222

Release

g++ -c -O2 -MMD -MP -MF build/Release/GNU-Linux-x86/foo.o.d -o build/Release/GNU-Linux-x86/foo.o foo.cpp

Whatever

RUN FAILED (exit value 1, total time: 49ms)

Class

#include "foo.h"
#define NUMINSIDE 10

foo::foo()
{
    inside = new int[NUMINSIDE];
}

void foo::workerFunc(int input)
{
    for (int i = 0; i < NUMINSIDE; i++)
    {
        inside[i] += input;
    }
}

void foo::operate()
{
    std::cout << "Whatever" << std::endl;
    boost::thread thA(boost::bind(&foo::workerFunc, this, 1));
    boost::thread thB(boost::bind(&foo::workerFunc, this, 1));
    thA.join();
    thB.join();
    for (int i = 0; i < NUMINSIDE; i++)
    {
        std::cout << this->inside[i] << std::endl;
    }
}

main

int main(int argc, char** argv)
{
    foo* myFoo = new foo();
    myFoo->operate();
    return 0;
}

Upvotes: 2

Views: 634

Answers (1)

ks1322
ks1322

Reputation: 35716

You have not initialized inside array. Add initialization code to foo::foo()

foo::foo()
{
    inside = new int[NUMINSIDE];
    for (int i = 0; i < NUMINSIDE; i++)
    {
        inside[i] = 0;
    }
}

It works only in debug because it is undefined behavior.

Upvotes: 1

Related Questions