【问题标题】:Boost::threads work in debug, don't in releaseBoost::threads 在调试中工作,不在发布中
【发布时间】:2011-11-07 11:59:17
【问题描述】:

我大约一个小时前开始做线程,但在调试模式达到我期望的效果和发布模式兑现时遇到了一些麻烦。

调试

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

随便 2222222222

发布

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

随便

RUN FAILED(退出值1,总时间:49ms)

#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;
    }
}

主要

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

【问题讨论】:

  • 这看起来不错,foo.h 的内容是什么?
  • 我看不到任何可能导致“RUN FAILED”输出的代码,所以问题可能出在您没有显示的某些代码中?

标签: c++ multithreading debugging gcc boost-thread


【解决方案1】:

您还没有初始化inside 数组。给foo::foo()添加初始化代码

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

它只适用于调试,因为它是未定义的行为。

【讨论】:

  • 虽然这是真的,但我怀疑它是造成崩溃的原因。
  • 除了内存泄漏,我没有看到任何其他问题
  • 疯了,但这似乎解决了它。奇怪的是,我构建类似的代码没有问题。它只会在一些垃圾内存上运行。
  • "奇怪的是,我在构建类似的代码时没有遇到任何问题。"没关系。如果您正在调用 UB,那么任何事情都可能发生 - 崩溃,对垃圾值进行操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
相关资源
最近更新 更多