[英]Message passing between threads in C
我試圖讓線程A與線程B進行通信。我應該使用線程之間的消息傳遞來做到這一點,但我試圖找到一些解釋消息傳遞的示例源代碼。
有沒有人有一些很好的鏈接到一些示例源代碼(在C中)解釋消息傳遞?
至少在Linux上相當快的方法是使用TCP或UDP套接字來在線程之間傳遞消息。 Linux內核非常聰明,如果我沒記錯的話,它將繞過網絡堆棧,這使得它非常快。 然后您不必擔心鎖定以及基本上由內核處理的各種其他問題。 應該足夠好做家庭作業。
進程中的每個線程都可以看到其他線程的所有內存。 如果兩個線程持有指向內存中相同位置的指針,則它們都可以訪問它。
以下是代碼但未經過測試。
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.