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
Try something like the following. You could make the class a thread-safe singleton and you could even make it a functor.
#include #include #include class ThreadPrioFun { typedef std::multimap 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(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; };