Listing 1

#include <pthread.h>

pid_t child_pid;
struct sched_param old_param;
struct pthread_mutex_t mutex;

void raise_child_priority()
{
  struct sched_param current;

  // Get the priority of the current thread
  sched_getparam(0, &current);

  // Get the priority of the child thread
  sched_getparam(child_pid, &old_param);

  // If the current thread's priority is greater than the
  // child's priority, raise the child's priority
  if(current.sched_priority > old_param.sched_priority) {
    sched_setparam(child_pid, &current);
  }
}

void lower_child_priority()
{
  // Set the child thread's priority back to its old priority
  sched_setparam(child_pid, &old_param);
}

int access_shared_resource()
{
  // First, try to get a lock on the resource
  if(pthread_mutex_trylock(&mutex) < 0) {
    if(errno == EBUSY) {
      // The other thread has the resource, 
      // raise its priority then perform a blocking lock
      raise_child_priority();
      if(pthread_mutex_lock(&mutex) < 0) return -1;
    }
    else {
      return -1;
    }
  }

  // Lower the child's priority back to normal
  lower_child_priority();

  /* Do stuff with the locked resource */

  // Release the lock
  if(pthread_mutex_unlock(&lock) < 0) return -1;
  return 0;
}