简体   繁体   English

提供互斥锁以更正线程

[英]Giving mutex to correct thread

If two threads are being blocked on a lock, how can you choose which get's it? 如果两个线程被锁定在一个锁上,那么您如何选择得到哪个呢?

For example thread1 calls mutex_lock(aMut) but aMut is already locked so thread1 blocks. 例如, thread1调用了mutex_lock(aMut)aMut已被锁定,因此thread1阻塞了。 Along comes thread2 and it calls mutex lock on aMut and it blocks. 随之而来的是thread2 ,它在aMut上调用互斥锁并阻塞。 How can it be ensured aMut is given to thread2 ? 如何确保将aMut分配给thread2

here is my attempt that doesn't work 这是我的尝试不起作用

/*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);
}

Just saying "Now I want this task to be scheduled and now this one" is not possible, but some thread libraries allow to set the priority of tasks, so it will be favored when scheduling. 只是说“现在我要安排这个任务,现在要安排这个任务”是不可能的,但是某些线程库允许设置任务的优先级,因此在计划时会受到青睐。

For pthreads, you can do this with pthread_getschedparam . 对于pthread,可以使用pthread_getschedparam进行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM