我想让A线程和B线程进行通信。我应该使用线程间的消息传递来实现这一点,但我正在寻找一些解释消息传递的示例源代码。
有没有人有一些好的链接提供消息传递的示例源代码(用C语言编写)?
我想让A线程和B线程进行通信。我应该使用线程间的消息传递来实现这一点,但我正在寻找一些解释消息传递的示例源代码。
有没有人有一些好的链接提供消息传递的示例源代码(用C语言编写)?
进程中的每个线程都可以看到其他线程的所有内存。如果两个线程持有指向内存中相同位置的指针,则它们都可以访问该位置。
以下是代码但未经测试。
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)
}
}
std::queue
。 - Some programmer dude