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

Create ptread_detach. #11

Closed joaovitorteixeira closed 2 years ago

joaovitorteixeira commented 3 years ago

pthread_detach function implementation:

int pthread_detach(pthread_t pthread)
{
    int iStatus = 0;
    pthread_internal_t * pxThread = ( pthread_internal_t * ) pthread;
    eTaskState pThreadState;

    /* Make sure pthread is joinable. */
    if( !pthreadIS_JOINABLE( pxThread->xAttr.usSchedPriorityDetachState ) )
    {
        iStatus = EINVAL;
    }

    if ( iStatus == 0 )
    {
        /* Create a critical section to verify that pthread is joinable. */
        vTaskSuspendAll();

        pThreadState = eTaskGetState(pxThread->xTaskHandle);

        /* Thread has been deleted or is invalid. */
        if ( (pThreadState == eDeleted) || (pThreadState == eInvalid) )
        {
           iStatus = EINVAL;
        }
        else
        {
           /* Release xJoinBarrier and delete it. */
            ( void ) xSemaphoreGive( ( SemaphoreHandle_t ) &pxThread->xJoinBarrier );
            vSemaphoreDelete( ( SemaphoreHandle_t ) &pxThread->xJoinBarrier );

            /* Release xJoinMutex and delete it. */
            ( void ) xSemaphoreGive( ( SemaphoreHandle_t ) &pxThread->xJoinMutex );
            vSemaphoreDelete( ( SemaphoreHandle_t ) &pxThread->xJoinMutex );

            /* Thread has been finished */
            if ( pThreadState == eSuspended )
            {
               /* Delete the FreeRTOS task that ran the thread. */
               vTaskDelete( pxThread->xTaskHandle );

               /* Free the thread object. */
               vPortFree( pxThread );
            }
            else
            {
               /* Thread is in the running or ready state. */
               pthread_attr_setdetachstate( (pthread_attr_t *) &pxThread->xAttr, PTHREAD_CREATE_DETACHED );
            }
        }

        /* End the critical section. */
        xTaskResumeAll();
    }

    return iStatus;
}

For this solution it can work correctly is necessary to add INCLUDE_eTaskGetState configuration. If this way is not the best solution, i can changed it. I do some unit tests, if you want to see I can publish the project.