/*
==================
Sys_EnterCriticalSection
==================
*/
void Sys_EnterCriticalSection( int index ) {
	assert( index >= 0 && index < MAX_LOCAL_CRITICAL_SECTIONS );
#ifdef ID_VERBOSE_PTHREADS	
	if ( pthread_mutex_trylock( &global_lock[index] ) == EBUSY ) {
		Sys_Printf( "busy lock %d in thread '%s'\n", index, Sys_GetThreadName() );
		if ( pthread_mutex_lock( &global_lock[index] ) == EDEADLK ) {
			Sys_Printf( "FATAL: DEADLOCK %d, in thread '%s'\n", index, Sys_GetThreadName() );
		}
	}	
#else
	pthread_mutex_lock( &global_lock[index] );
#endif
}
/*
========================
Sys_DestroyThread
========================
*/
void Sys_DestroyThread( uintptr_t threadHandle )
{
    if( threadHandle == 0 )
    {
        return;
    }

    char	name[128];
    name[0] = '\0';

#if defined(DEBUG_THREADS)
    Sys_GetThreadName( ( pthread_t )threadHandle, name, sizeof( name ) );
#endif

#if 0 //!defined(__ANDROID__)
    if( pthread_cancel( ( pthread_t )threadHandle ) != 0 )
    {
        idLib::common->FatalError( "ERROR: pthread_cancel %s failed\n", name );
    }
#endif

    if( pthread_join( ( pthread_t )threadHandle, NULL ) != 0 )
    {
        idLib::common->FatalError( "ERROR: pthread_join %s failed\n", name );
    }
}
/*
==================
Sys_LeaveCriticalSection
==================
*/
void Sys_LeaveCriticalSection( int index ) {
	assert( index >= 0 && index < MAX_LOCAL_CRITICAL_SECTIONS );
#ifdef ID_VERBOSE_PTHREADS
	if ( pthread_mutex_unlock( &global_lock[index] ) == EPERM ) {
		Sys_Printf( "FATAL: NOT LOCKED %d, in thread '%s'\n", index, Sys_GetThreadName() );
	}
#else
	pthread_mutex_unlock( &global_lock[index] );
#endif
}