这与我一直在讨论的一个问题有关here和 here ,但由于我的调查使我不再将 STL 作为潜在问题,而是将"new"作为我的克星,我认为最好开始一个新线程。
重申一下,我使用的是嵌入式平台供应商提供的 arm-linux 交叉编译器(版本 2.95.2)。
当我在我的 Linux PC 上运行下面的应用程序时,它当然可以正常运行。但是,在嵌入式设备上运行它时,我每次都会遇到段错误。使用“malloc”永远不会失败。使用互斥锁同步"new"分配将解决问题,但这在我的主要应用程序中不切实际。
任何人都可以建议为什么会发生这种情况,或者有任何想法可以解决这个问题吗?
谢谢。
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t _logLock = PTHREAD_MUTEX_INITIALIZER;
static void* Thread(void *arg)
{
int i = 0;
while (i++ < 500)
{
// pthread_mutex_lock(&_logLock);
char* myDyn = (char*) new char[1023];
// char* buffer = (char*) malloc(1023);
// if (buffer == NULL)
// printf("Out of mem\n");
// free(buffer);
delete[] myDyn;
//pthread_mutex_unlock(&_logLock);
}
pthread_exit(NULL);
}
int main(int argc, char** argv)
{
int threads = 50;
pthread_t _rx_thread[threads];
for (int i = 0; i < threads; i++)
{
printf("Start Thread: %i\n", i);
pthread_create(&_rx_thread[i], NULL, Thread, NULL);
}
for (int i = 0; i < threads; i++)
{
pthread_join(_rx_thread[i], NULL);
printf("End Thread: %i\n", i);
}
}
最佳答案
如果您设备上的堆不是线程安全的,那么您需要锁定。您可以只编写自己的 new 和 delete 函数,在 new 或 delete 期间锁定——您不需要在分配的内存的整个生命周期内保持锁定。
检查是否有编译器开关使分配器线程安全。
关于c++ - "new"operator in multiple threads cause Segmentation Fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3576258/