Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"new" operator in multiple threads causes Segmentation Fault

This is related to an issue I have been discussing here and here, but as my investigations have led me away from the STL as the potential issue, and towards "new" as my nemisis, I thought it best to start a new thread.

To reiterate, I am using an arm-linux cross compiler (version 2.95.2) supplied by the embedded platform vendor.

When I run the application below on my Linux PC, it of course works never fails. However when running it on the embedded device, I get segmentation faults every time. Using "malloc" never fails. Synchronising the "new" allocation using the mutex will stop the issue, but this is not practical in my main application.

Can anyone suggest why this might be occurring, or have any ideas how I can get around this issue?

Thanks.

#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);
    }
}
like image 842
Brad Avatar asked Jun 04 '26 04:06

Brad


1 Answers

If the heap on your device isn't thread-safe, then you need to lock. You could just write your own new and delete functions that lock for the duration of new or delete -- you don't need to hold the lock across the whole lifetime of the allocated memory.

Check to see if there are compiler switches to make the allocator thread-safe.

like image 154
Lou Franco Avatar answered Jun 05 '26 18:06

Lou Franco