How to give priority to privileged thread in mutex locking?

后端 未结 8 1213
失恋的感觉
失恋的感觉 2020-12-01 02:48

First of all: I am completely a newbie in mutex/multithread programming, so sorry for any error in advance...

I have a program that runs multiple threads. The threads

相关标签:
8条回答
  • 2020-12-01 03:41

    On linux you can check this man: pthread_setschedparam and also man sched_setscheduler

    pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param);

    Check this also for c++2011: http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx#Y78

    0 讨论(0)
  • 2020-12-01 03:42

    Try something like the following. You could make the class a thread-safe singleton and you could even make it a functor.

    #include <pthread.h>
    #include <semaphore.h>
    #include <map>
    
    class ThreadPrioFun
    {
        typedef std::multimap<int, sem_t*> priomap_t;
    public:
        ThreadPrioFun()
        {
            pthread_mutex_init(&mtx, NULL);
        }
        ~ThreadPrioFun()
        {
            pthread_mutex_destroy(&mtx);
        }
        void fun(int prio, sem_t* pSem)
        {
            pthread_mutex_lock(&mtx);
            bool bWait = !(pm.empty());
            priomap_t::iterator it = pm.insert(std::pair<int, sem_t*>(prio, pSem) );
            pthread_mutex_unlock(&mtx);
    
            if( bWait ) sem_wait(pSem);
    
            // do the actual job
            // ....
            //
    
            pthread_mutex_lock(&mtx);
            // done, remove yourself
            pm.erase(it);
            if( ! pm.empty() )
            {
                 // let next guy run:
                sem_post((pm.begin()->second));
            }
            pthread_mutex_unlock(&mtx);
        }
    private:
        pthread_mutex_t mtx;
        priomap_t pm;
    };
    
    0 讨论(0)
提交回复
热议问题