I will be discussing the function thrd_detach(), from the threads.h header of the new c11, which is also included in the latest pelles ide.
( the thread I wil refer below will always be the thread created, not the main thread; the main never exists in examples below )
The only information I can find on the function thrd_detach() is from the pelles help and this:
http://en.cppreference.com/w/c/thread/thrd_detach. Both basically say the same thing( please read them if you haven't ).
I interpret the description offered in those documents that the function can detach the thread before the thread actually exits. Furthermore it states that the function resources will be freed automatically when the thread exits, implying that thrd_detach() can detach a thread before the thread exited.
That is the problem; thrd_detach() works fine when the thread in question already exited. But if the thread was still running when thrd_detach() was called, it causes an exception violation when the thread exists, ( not when you call thrd_detach() )
Is that the desired behavior? ( if it is, it goes against the logic of the description, in my opinion )
Here is the example which is described in words above.
#include <threads.h>
#include <assert.h>
#include <stdio.h>
//#define THREAD_EXITS_BEFORE_DETACH_CALL //doesn't crash if this is defined
#ifdef THREAD_EXITS_BEFORE_DETACH_CALL
long long int delay_thread = 10 ;
long long int delay_main = 1000000 ;
#else
long long int delay_thread = 1000000 ;
long long int delay_main = 10 ;
#endif
int Thread( void* d )
{
( void )d ;
long long int i = 0 ;
while( i++ < delay_thread )
thrd_yield() ;
printf("thread done\n") ;
return 0 ;
}
int main( void )
{
thrd_t t ;
int v = thrd_create( &t , Thread , NULL ) ;
assert( v == thrd_success ) ;
long long int i = 0 ;
while( i++ < delay_main )
thrd_yield() ;
printf("detach now\n") ;
int b= thrd_detach( t ) ;
assert( b == thrd_success ) ;
printf("done\n") ;
while( 1 )
{
thrd_yield() ;//leave the main thread running
}
return 0 ;
}
If you have a different compiler that supports c11 and threads.h please try the crash version of the above code example.
I using windows7 32 bit version, Pelles 7.00.355, and optimizations disabled.