How to allow certain threads to have priority in locking a mutex use PTHREADS

前端 未结 6 1244
天命终不由人
天命终不由人 2020-12-15 23:32

Assume that the following code is being executed by 10 threads.

pthread_mutex_lock(&lock)
Some trivial code
pthread_mutex_unlock(&lock)
6条回答
  •  被撕碎了的回忆
    2020-12-16 00:20

    Alternatively you may just introduce another lock for higher priority threads. consider the following pseudo-code (i am not familiar with the pthread semantics, but i believe this is not hard to map the code to the needed calls)

    EDIT (thanx JosephH)

    introducing the exec semaphore set to 3 (number of high-prio threads) note that pend(exec,3); means that this pend will sleep until all 3 slots are available and will consume them all

    
    
    //init
    exec = semaphore(3,3);
    
    //========================
    
    if this is NOT thread (t1,t2,t3)
        lock(low_prio);
        sem_pend(exec,3);
    else
        sem_pend(exec,1);
    lock(high_prio);
    //...
    unlock(high_prio);
    if this is NOT thread (t1,t2,t3)
        sem_release(exec,3);
        sleep(0); //yield();  //ensures that sem_pend(exec,1) is executed
        unlock(low_prio);
    else
        sem_release(exec,1);
    

提交回复
热议问题