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

前端 未结 6 1248
天命终不由人
天命终不由人 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:23

    (The first two attempts had bugs, pls jump to EDIT2)

    Maybe this would work?

    if NOT this thread is T1 or T2 or T3
        pthread_mutex_lock(&lock1) // see note below
        pthread_mutex_lock(&lock2)
        Some trivial code
        pthread_mutex_unlock(&lock2)
        pthread_mutex_unlock(&lock1)
    else
        pthread_mutex_lock(&lock2)
        Some trivial code
        pthread_mutex_unlock(&lock2)        
    end if
    

    Reasoning: Some threads will compete for two locks and therefore will have lower priority and some threads will compete for only one lock and therefore will have higher priority. Still the difference might be marginal and then the resolution would be to introduce some lag between acquiring first lock and attempting the second lock for the higher priority threads in which time the higher priority threads will be given a chance to get the lock2.
    (disclaimer: I am a newbie when it comes to this)

    EDIT: Another attempt/approach

    if NOT (this thread is T1 or T2 or T3)  
        pthread_mutex_lock(&lock1)
        if pthread_mutex_trylock(&lock2) == 0  // low priority threads will not get queued
            Some trivial code
            pthread_mutex_unlock(&lock2)
        end if
        pthread_mutex_unlock(&lock1)
    else 
        if (this thread is T1 or T2 or T3)
            pthread_mutex_lock(&lock2)
            Some trivial code
            pthread_mutex_unlock(&lock2)        
        end if
    end if
    

    EDIT2: Another attempt (trying to learn something here)

    if NOT (this thread is T1 or T2 or T3)  
        pthread_mutex_lock(&lock1)
        while !(pthread_mutex_trylock(&lock2) == 0)
            pthread_yield()
        Some trivial code
        pthread_mutex_unlock(&lock2)
        pthread_mutex_unlock(&lock1)
    else 
        if (this thread is T1 or T2 or T3)
            pthread_mutex_lock(&lock2)
            Some trivial code
            pthread_mutex_unlock(&lock2)        
        end if
    end if
    

提交回复
热议问题