Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe Message Queue with multiple threads

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.

The problem arises when B and C or B or C try to send a message to A while A is processing a message and thus accessing the queue.

How is this problem usually solved?

Thanks

like image 651
jmasterx Avatar asked Oct 16 '11 01:10

jmasterx


1 Answers

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.

like image 152
Nate Avatar answered Oct 06 '22 13:10

Nate