Assume that the following code is being executed by 10 threads.
pthread_mutex_lock(&lock)
Some trivial code
pthread_mutex_unlock(&lock)
To implement that with pthreads you would need N lists, one per thread priority. The lists would contain pointers to the thread's pthread_cond_t variables.
Schematic untested meta-code:
/* the main lock */
pthread_mutex_t TheLock = PTHREAD_MUTEX_INITIALIZER;
/* service structures: prio lists and the lock for them */
pthread_mutex_t prio_list_guard = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t *prio_lists[MY_MAX_PRIO][MY_MAX_THREAD]; /* 0 == highest prio */
/* lock */
void
prio_lock(int myprio)
{
pthread_cond_t x;
pthread_mutex_lock( &prio_list_guard );
if (0 == pthread_mutex_trylock( &TheLock )) {
pthread_mutex_unlock( &prio_list_guard );
return 0;
}
pthread_cond_init( &x, 0 );
LIST_ADD( prio_lists[myprio], &x )
while(1) /* handle spurious wake-ups */
{
pthread_cond_wait( &prio_list_guard, &x );
if (0 == pthread_mutex_trylock( &TheLock ))
{
LIST_REMOVE( prio_lists[myprio], &x );
pthread_mutex_unlock( &prio_list_guard );
return 0;
}
}
}
/* unlock */
void
prio_unlock()
{
int i;
pthread_cond_t *p;
pthread_mutex_lock( &prio_list_guard );
for (i=0; i
The code also handles spurious wake-ups from pthread_cond_wait(), but frankly I have never seen that happening.
Edit1. Note that prio_lists above is a primitive form of a priority queue.