POSIX Thread: Setting Priority and Stack Size

Legendary ThreadThe POSIX Thread library, also known as pthread, has always annoyed me with trying to set thread priority.

Some documentation for pthread_attr_setschedparam() say use PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY, however they never seem to exist.

Some sites say use 0 and 31 for them respectively for min and max.

Instead I found a function that will retrieve the min and max priority for a given scheduling policy, allowing you to set the thread priority before it is created.

void SetAttributeMaxPriority( pthread_attr_t & inThreadAttr )
{
	const int kPolicy = SCHED_RR;
	int minPriority = sched_get_priority_min( kPolicy );
	int maxPriority = sched_get_priority_max( kPolicy );
 
	//
	sched_param schedParam;
	schedParam.sched_priority = maxPriority;
	pthread_attr_setschedparam( &inThreadAttr, &schedParam );
 
	//
	pthread_attr_setschedpolicy( &inThreadAttr, kPolicy );
}

 

The stack size also needs to be a multiple of the page size, while this is not really an issue unless you go really low or don’t use a power of 2 number, I added some code to reinforce it.

void SetStackSize( pthread_attr_t & inThreadAttr, const int inStackSize )
{
	//
	int stackSize = ( inStackSize < PTHREAD_STACK_MIN ) ? PTHREAD_STACK_MIN : inStackSize;
 
	//
	int pageSize = sysconf( _SC_PAGESIZE );
	if( pageSize == -1 )
	{
		pageSize = PTHREAD_STACK_MIN;
	}
 
	int multipleRemainder = mParams.stackSize % pageSize;
	if( multipleRemainder != 0 )
	{
		stackSize += ( pageSize - multipleRemainder );
	}
 
	//
	pthread_attr_setstacksize( &inThreadAttr, stackSize );
}

 

I wasn’t sure if _SC_PAGESIZE would work on every system, so just incase I made page size equal PTHREAD_STACK_MIN if an error was returned.