Race condition during thread creation

I had strange random errors with threads. I suspect race condition during thread creation, can somebody confirm this? My example code is:

static void thread_body (ULONG initial_input)
{
 while(1);
}

void thread_creator()
{
 TX_THREAD my_thread = {0};

 //stack malloc here
 tx_thread_create (&my_thread, "thread name", &thread_body ........);
}

// somewere else (ie. root.c)

thread_creator();

It looks like thread creation is sometime delayed, but tx_thread_create ends and my function ends, so local varial my_thread is no longer available. Is it true, or I have error somewhere else?

Hi,

I am afraid that this code will not operate correctly.
The TX_THREAD structure is the control block for the thread, and would normally be a GLOBAL variable. Your code is allocating this structure on the stack.

It may be possioble to do this by using malloc to generate TX_THREAD structures, in the same way that you are doing for the thread stacks.

I suspect that you will also need some way of tracking the memory allocated for the TX_THREADS and stacks, so that you can recover the memory once you have finished with the threads.

You can do it either via mallocing the thread control block or declaring the thread control block in a global sort of way. Either way, the thread control block can NOT be a stack variable that will disappear when your thread creation function goes out of scope.