WORKER_THREAD_HANDLE worker_thread_create()

in src/worker_thread.c [79:126]


WORKER_THREAD_HANDLE worker_thread_create(WORKER_FUNC worker_func, void* worker_func_context)
{
    WORKER_THREAD_HANDLE worker_thread;

    /* Codes_SRS_WORKER_THREAD_01_004: [ worker_func_context shall be allowed to be NULL. ]*/

    /* Codes_SRS_WORKER_THREAD_01_003: [ If worker_func is NULL, worker_thread_create shall fail and return NULL. ]*/
    if (worker_func == NULL)
    {
        LogError("NULL worker_func");
    }
    else
    {
        /* Codes_SRS_WORKER_THREAD_01_001: [ worker_thread_create shall allocate memory for a new worker thread object and on success return a non-NULL handle to it. ]*/
        worker_thread = malloc(sizeof(WORKER_THREAD));
        if (worker_thread == NULL)
        {
            /* Codes_SRS_WORKER_THREAD_01_008: [ If any error occurs, worker_thread_create shall fail and return NULL. ]*/
            LogError("Cannot allocate memory for BS worker thread");
        }
        else
        {
            worker_thread->worker_func = worker_func;
            worker_thread->worker_func_context = worker_func_context;

            /* Codes_SRS_WORKER_THREAD_01_037: [ worker_thread_create shall create a state manager object by calling sm_create with the name worker_thread. ]*/
            worker_thread->sm = sm_create("worker_thread");
            if (worker_thread->sm == NULL)
            {
                LogError("sm_create failed");
            }
            else
            {
                /* Codes_SRS_WORKER_THREAD_01_022: [ worker_thread_create shall perform the following actions in order: ]*/

                /* Codes_SRS_WORKER_THREAD_01_006: [ worker_thread_create shall initialize the state object. ]*/
                (void)interlocked_exchange(&worker_thread->state, WORKER_THREAD_STATE_IDLE);
                goto all_ok;
            }

            free(worker_thread);
        }
    }
    worker_thread = NULL;

all_ok:
    return worker_thread;
}