7

I am trying to get Thread A to communicate with Thread B. I should be using message passing between threads to do this but I am trying to find some sample source code which explains message passing.

Does anyone have any good link to some sample source code (in C) which explains message passing ?

IanNorton
  • 7,145
  • 2
  • 25
  • 28
Ashish Agarwal
  • 14,555
  • 31
  • 86
  • 125

3 Answers3

13

While not having a link, there are many ways to implement this.

  • First is to use sockets. This is not actually a method I would recommend, as it can be quite a lot of work to get it to work right.

  • The second is related to the first method, and is to use something called anonymous pipes.

  • A third way, and the one I usually use, is "inspired" by how message passing worked on the old Amiga operating system: Simply use a queue. Since memory is shared between threads it's easy to just pass pointers around. Use one queue per thread. Just remember to protect the queues, with something like a mutex.

  • The platform you are using will probably have other ways of communication. Do a Google search for (for example) linux ipc.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

ONe very easy way that's fairly fast on Linux at least is to use either TCP or UDP sockets for message passing between threads. The Linux kernel is pretty smart and if I remember correctly it will bypass the network stack which makes it pretty fast. Then you don't have to worry about locking and various other issues which are basically handled by the kernel. Should be good enough for a homework assignment.

Uri's TCP/IP Resources List FAQs, tutorials, guides, web pages & sites, and books about TCP/IP

Robert S. Barnes
  • 39,711
  • 30
  • 131
  • 179
1

Each thread in a process can see all of the memory of other threads. If two threads hold a pointer to the same location in memory, then they can both access it.

Following is the code but not tested.

struct MessageQueue
{
    std::queue<std::string> msg_queue;
    pthread_mutex_t mu_queue;
    pthread_cond_t cond;
};

{
    // In a reader thread, far, far away...
    MessageQueue *mq = <a pointer to the same instance that the main thread has>;
    std::string msg = read_a_line_from_irc_or_whatever();
    pthread_mutex_lock(&mq->mu_queue);
    mq->msg_queue.push(msg);
    pthread_mutex_unlock(&mq->mu_queue);
    pthread_cond_signal(&mq->cond);
}

{
    // Main thread
    MessageQueue *mq = <a pointer to the same instance that the main thread has>;

    while(1)
    {
        pthread_mutex_lock(&mq->mu_queue);
        if(!mq->msg_queue.empty())
        {
            std::string s = mq->msg_queue.top();
            mq->msg_queue.pop();
            pthread_mutex_unlock(&mq->mu_queue);
            handle_that_string(s);
        }
        else
        {
            pthread_cond_wait(&mq->cond, &mq->mu_queue)
        }
    }
Avinash
  • 12,851
  • 32
  • 116
  • 186