Safe Message Queue with multiple threads

前端 未结 2 978
深忆病人
深忆病人 2021-02-06 12:00

Here is what I essentially have:

I have thread A that periodically checks for messages and processes them.

Threads B and C need to send messages to A.

Th

2条回答
  •  长情又很酷
    2021-02-06 12:30

    This is normally solved using mutexes, or other multi-thread protection mechanisms.

    If you are working on windows, MFC provides the CMutex class for this problem.

    If you are working on a posix system, the posix api provides the pthread_mutex_lock, pthread_mutex_unlock, and pthread_mutex_trylock functions.

    Some basic pseudocode would be handy to demonstrate their use in your case:

    pthread_mutex_t mutex; *or* CMutex mutex;
    Q queue;  // <-- both mutex and queue are global state, whether they are
              //     global variables, or passed in as parameters, they must
              //     be the shared by all threads.
    
    int threadA(/* params */){
        while( threadAStillRunning ){
            // perform some non-critical actions ...
            pthread_mutex_lock(mutex) *or* mutex.Lock()
            // perform critical actions ...
            msg = queue.receiveMessage()
            pthread_mutex_unlock(mutex) *or* mutex.Unlock()
            // perform more non-critical actions
        }
    }
    
    int threadBorC(/* params */){
        while( theadBorCStillRunning ){
            // perform some non-critical actions ...
            pthread_mutex_lock(mutex) *or* mutex.Lock()
            // perform critical actions ...
            queue.sendMessage(a_msg)
            pthread_mutex_unlock(mutex) *or* mutex.Unlock()
        }
    }
    

    For all three threads, their ability to act on the queue hinges on their ability to acquire the mutex - they will simply block and wait until the mutex is acquired. This prevents conflicts arising from the use of that resource.

提交回复
热议问题