消息在C中的线程之间传递

时间:2011-11-24 07:04:04

标签: c multithreading

我试图让线程A与线程B进行通信。我应该使用线程之间的消息传递来做到这一点,但我试图找到一些解释消息传递的示例源代码。

有没有人有一些很好的链接到一些示例源代码(在C中),它解释了消息传递?

3 个答案:

答案 0 :(得分:11)

虽然没有链接,但有很多方法可以实现这一点。

  • 首先是使用套接字。这实际上不是我推荐的方法,因为要使它正常工作可能需要做很多工作。

  • 第二种方法与第一种方法有关,就是使用一种叫做匿名管道的东西。

  • 第三种方式,也就是我经常使用的方式,受到旧Amiga操作系统上消息传递的启发“启发”:只需使用queue。由于内存在线程之间共享,因此很容易传递指针。每个线程使用一个队列。请记住保护队列,例如mutex

  • 您正在使用的平台可能还有其他沟通方式。谷歌搜索(例如) linux ipc

答案 1 :(得分:2)

ONe非常简单,在Linux上相当快,至少是使用TCP或UDP套接字在线程之间传递消息。 Linux内核非常聪明,如果我没记错的话,它将绕过网络堆栈,这使得它非常快。然后您不必担心锁定以及基本上由内核处理的各种其他问题。应该足够好做家庭作业。

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

答案 2 :(得分:0)

进程中的每个线程都可以看到其他线程的所有内存。如果两个线程持有指向内存中相同位置的指针,则它们都可以访问它。

以下是代码,但未经过测试。

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)
        }
    }