Suspend pthreads without using condition

前端 未结 6 996
眼角桃花
眼角桃花 2020-12-16 05:09

I want to suspend pthreads but apparently, there is no such function as pthread_suspend. I read somewhere about suspending pthreads using mutexes and conditions and used it

6条回答
  •  长情又很酷
    2020-12-16 05:35

    Your code is not correct - the pthread_cond_wait() requires that the mutex be locked already when you call it:

    void suspendMe()
    {
        pthread_mutex_lock(&m_SuspendMutex);
        pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
        pthread_mutex_unlock(&m_SuspendMutex);
    }
    

    However, this is still wrong. A thread can wake up from pthread_cond_wait() at any name, not necessarily only when it is signalled. This means that you need to pair pthread_cond_wait() with some shared state that encodes the condition that the thread is really waiting for - in the simplest case, you can just use a flag variable. pthread_cond_signal() is used to tell the thread that it should wake and re-check the shared state. Applying this to your implementation:

    class PThread {
        public:
    
        pthread_t myPthread;
        bool suspended;
        pthread_mutex_t m_SuspendMutex;
        pthread_cond_t m_ResumeCond;
    
        void start() {
            suspended = false;
            pthread_create(&myPthread, NULL, threadRun, (void*)this );
        }
    
        Thread() { }
    
        void suspendMe() {
            pthread_mutex_lock(&m_SuspendMutex);
            suspended = true;
            do {
                pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
            } while (suspended);
            pthread_mutex_unlock(&m_SuspendMutex);
        }
    
        void resume() {
            /* The shared state 'suspended' must be updated with the mutex held. */
            pthread_mutex_lock(&m_SuspendMutex);
            suspended = false;
            pthread_cond_signal(&m_ResumeCond);
            pthread_mutex_unlock(&m_SuspendMutex);
        }
    };
    

    The reason the mutex is provided is to protect the shared state and avoid race conditions - the pthread_cond_wait() function actually performs an atomic-unlock-and-wait when it waits, which allows a "missed wakeup" to be avoided. For example in this code, the mutex prevents suspended from changing to false in between the suspended = true; and pthread_cond_wait() lines.

提交回复
热议问题