FreeRTOS / Lab-Project-FreeRTOS-POSIX

This repository contains FreeRTOS+POSIX source code, which could be consumed as a submodule.
MIT License
95 stars 60 forks source link

How to deal with large stacksize in pthread_attr_setstacksize() #20

Closed frdmu closed 1 year ago

frdmu commented 1 year ago

When using this function

int pthread_attr_setstacksize( pthread_attr_t * attr,
                               size_t stacksize )
{
    int iStatus = 0;
    pthread_attr_internal_t * pxAttr = ( pthread_attr_internal_t * ) ( attr );

    if( stacksize < PTHREAD_STACK_MIN )
    {
        iStatus = EINVAL;
    }
    else
    {
        pxAttr->usStackSize = ( uint16_t ) stacksize;
    }

    return iStatus;
}

For

pxAttr->usStackSize = ( uint16_t ) stacksize;

when I have to set stacksize = 512 * 1024 in my new pthread,
after doing this,

pxAttr->usStackSize = (uint16_t)(512 * 1024) = 0

and cause a pvPortMalloc failed error. Can I just change this to

pxAttr->usStackSize = ( uint32_t ) stacksize;
dachalco commented 1 year ago

Hi @frdmu

The malloc error seems to indicate that 500 KB is too much for configured heap. How much available heap do you have? Ports that use FreeRTOS heap have configTOTAL_HEAP_SIZE in FreeRTOSConfig.h which you can increase within the device's capacity. Alternatively, you can create a static task and entirely avoid the heap with regards to this task creation, and instead try xTaskCreateStatic.

You can not simply change pxAttr->usStackSize for immediate change in stack size. This configuration with pthread_attr_setstacksize is just meant to assign the value before calling pthread_create which actually references it once it's time for allocation.

n9wxu commented 1 year ago

You cannot change the code as you show because the usStackSize value in the pThread_attr_t is only 16-bit (unsigned).

https://github.com/FreeRTOS/Lab-Project-FreeRTOS-POSIX/blob/85ce51dad6aef44446c9f289e65f35c318afe015/FreeRTOS-Plus-POSIX/source/FreeRTOS_POSIX_pthread.c#L45 The pThread_attr_t must also have the usStackSize type changed to a uint32_t.

FreeRTOS uses hungarian notation so changing the type to a uint32_t will require that the usStackSize change name to uiStackSize which will have consequences everywhere that variable is used.

If you want to make this change we are happy to review your PR.