【问题标题】:Memory allocation problems when working with a class in a new thread在新线程中处理类时的内存分配问题
【发布时间】:2013-04-08 12:56:21
【问题描述】:

我有这样的代码和平:

#include "Item.h"
#include "Object.h"

int main(){

    Item Pan(0);

    Pan.Prep2Cook();


    //Object(char*, int);

    Object Drawer(Pan.Oil_Memory, Pan.Oil_Size);


    Drawer.Search();

    Pan.OilId = Drawer.Oil();

    Pan.Finish_Cooking();


    return 0;
}

它按预期工作,但如果我将其更改为:

#include "Item.h"
#include "Object.h"

DWORD WINAPI Cooky(LPVOID);


int main(){

    // tried changing to 1000000000, still gives the error...
    // tried changing to 0, still gives the error...

    CreateThread(0,100000,Cooky,LPVOID(0),0,0);

    /*...
    Do_Other_Stuff();
    ...*/


    return 0;
}

DWORD WINAPI Cooky(LPVOID lParam)
{

    Item Pan(int (lParam) );

    Pan.Prep2Cook();

    Object Drawer(Pan.Oil_Memory, Pan.Oil_Size);//memory allocating error here

    Drawer.Search();

    Pan.OilId = Drawer.Oil();

    Pan.Finish_Cooking();

    return 0;

}

在“抽屉”类中分配内存时会出现这样的问题:

data1 = new unsigned char[size];//error here

data2 = new unsigned char[size2];

all_data = new unsigned char*[9];

编辑:size 和 size2 等于或小于 10000。

我尝试在 Createthread 中使用 dwStackSize 参数“操纵”,但它仍然给我错误...

欢迎任何有关如何解决此错误的建议。

【问题讨论】:

  • 这些都没有分配在堆栈上,因此更改线程的堆栈大小无济于事。
  • “大小”设置为多少?
  • 线程的好处是你会有更多的代码来分配内存和工作。该奖章的另一面是您将不可避免地更快地耗尽虚拟内存。或者增加破坏堆的可能性,因为您没有充分保护共享状态。线程从不可以添加到并非设计为线程安全的代码中。

标签: c++ multithreading class memory allocation


【解决方案1】:

用这么少的代码很难判断你的错误是什么,但这里有一些你可能需要考虑的事情

你的主线程实际上在做什么

/*...
Do_Other_Stuff();
...*/

return 0; //this will immediatly end every single thread

很重要,如果您尝试按原样运行代码,您的主线程将结束并退出您的程序 如果你的程序在你分配内存失败时似乎崩溃了,那可能是因为这是你线程中的一个重要操作,当你尝试分配内存时你的程序退出了

其次,您分配给线程的堆栈大小无关紧要,因为分配失败是在堆上(因为您使用new)此外,分配给大量堆栈可能会阻碍分配,因为您只有有限的内存(但这可能不是问题)

【讨论】:

  • 好吧,我写 do_other_stuff() 是有原因的,我说得还不够清楚吗? (也许我不应该评论它......)。我也尝试使用 0 dwStacksize 值运行,结果是一样的...
猜你喜欢
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 2018-10-21
  • 1970-01-01
相关资源
最近更新 更多