我试图让线程A与线程B进行通信。我应该使用线程之间的消息传递来做到这一点,但我试图找到一些解释消息传递的示例源代码。
有没有人有一些很好的链接到一些示例源代码(在C中),它解释了消息传递?
答案 0 :(得分:11)
虽然没有链接,但有很多方法可以实现这一点。
答案 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)
}
}