"new" statement in multiple threads causes a segmentation error

This is due to the fact that I discussed here here and here , but as my investigation led me from the STL as a potential problem, and to the "new" as to my nemisis, I thought it best to start a new thread.

I repeat, I am using the arm-linux cross compiler (version 2.95.2) provided by the vendor of the embedded platform.

When I run the application below on my Linux PC, it certainly will never work. However, when I run on the embedded device every time I get segmentation errors. The use of "malloc" is never interrupted. Syncing the “new” distribution using the mutex will stop the problem, but this is not practical in my main application.

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

Thank.

#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);
    }
}
+3
source share
4 answers

, . , - .

, , .

+4

, , . ARM -, , , , .

, , () . , .

, , , , .

+2

, new, , . , , . Boost.thread library, , .

+1

How about using malloc (you say it never breaks on the embedded platform) to get the required memory and then use the new placement (void * operator new [] (std :: size_t size, void * ptr) throw () ), assuming it is available for construction. See new [] operator

Also fooobar.com/questions/21266 / ...

and MSDN

+1
source

Source: https://habr.com/ru/post/1761739/


All Articles