簡體   English   中英

消息在C中的線程之間傳遞

[英]Message passing between threads in C

我試圖讓線程A與線程B進行通信。我應該使用線程之間的消息傳遞來做到這一點,但我試圖找到一些解釋消息傳遞的示例源代碼。

有沒有人有一些很好的鏈接到一些示例源代碼(在C中)解釋消息傳遞?

雖然沒有鏈接,但有很多方法可以實現這一點。

  • 首先是使用套接字。 這實際上不是我推薦的方法,因為要使它正常工作可能需要做很多工作。

  • 第二種方法與第一種方法有關,並且使用一種稱為匿名管道的方法。

  • 第三種方式,也就是我經常使用的方式,受到舊Amiga操作系統上消息傳遞的影響“啟發”:只需使用隊列 由於內存在線程之間共享,因此很容易傳遞指針。 每個線程使用一個隊列。 只需記住保護隊列,就像互斥鎖一樣

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

至少在Linux上相當快的方法是使用TCP或UDP套接字來在線程之間傳遞消息。 Linux內核非常聰明,如果我沒記錯的話,它將繞過網絡堆棧,這使得它非常快。 然后您不必擔心鎖定以及基本上由內核處理的各種其他問題。 應該足夠好做家庭作業。

Uri的TCP / IP資源列表常見問題解答,教程,指南,網頁和網站以及有關TCP / IP的書籍

進程中的每個線程都可以看到其他線程的所有內存。 如果兩個線程持有指向內存中相同位置的指針,則它們都可以訪問它。

以下是代碼但未經過測試。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM