给互斥锁正确的线程

时间:2014-10-27 08:07:00

标签: c pthreads mutex

如果一个锁上有两个线程被阻止,你怎么能选择哪个线程?

例如thread1调用mutex_lock(aMut),但aMut已被锁定,因此thread1会阻止。一起来thread2,它会调用aMut上的互斥锁并阻止它。如何确保aMut被赋予thread2

这是我的尝试不起作用

/*global variables*/
pthread_mutex_t aMut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond_var = PTHREAD_COND_INITIIALIZER;
pthread_cond_t  changeNumPrior = PTHREAD_COND_INITIIALIZER;
int highPriorityThreads = 0;

/*function that is passed to pthread_create()*/
void* functionThatIsPassedToPthreadCreate(void* arg)
{
   bool highPriority = false;
   if(arg->someConditionIsMet)
   {
     highPriorityThreads++;
     highPriority = true;
   }
   pthread_mutex_lock(&changeNumPrior);
    while(!highPriority && highPriorities > 0)//this doesn't work
    {
        pthread_cond_wait(&cond_var, &changeNumPrior);
    }
    pthread_mutex_unlock(&changeNumPrior);

    pthread_mutex_lock(&aMut);//if this blocks, by the time this mutex is aquired, there now may be high priority threads
    //code that requires exclusive access to shared resource protected by aMut
    pthread_mutex_unlock(&aMut);
    pthread_cond_signal(&cond_var);
}

1 个答案:

答案 0 :(得分:0)

只是说"现在我想要安排这个任务,现在这个任务"是不可能的,但是一些线程库允许设置任务的优先级,因此在调度时会受到青睐。

对于pthread,您可以使用pthread_getschedparam执行此操作。