使用Message_Queue的经典的“有界缓冲区”的ACE实现

本文介绍了一个使用ACE库实现的线程间通信示例,通过Message_Queue进行消息传递。一个生产者线程读取标准输入并发送消息到队列,消费者线程从队列接收消息并写入标准输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "ace/Message_Queue.h"
#include "ace/Thread_Manager.h"
#include "ace/Synch_Traits.h"

typedef ACE_Message_Queue<ACE_MT_SYNCH> MT_Message_Queue;

// Global thread manager.

static ACE_Thread_Manager thr_mgr;

static int producer (MT_Message_Queue *msg_queue)

{

 // Insert thread into thr_mgr.

 ACE_Thread_Control tc (&thr_mgr);

 char buf[BUFSIZ];

 for (int n; ; )

 {

  // Allocate a new message.

  ACE_Message_Block *mb = new ACE_Message_Block (BUFSIZ);

  n = read (0, mb->rd_ptr (), mb->size ());

  if (n <= 0)

  {

   // Shutdown message to the other

   // thread and exit.

   mb->length (0);

   msg_queue->enqueue_tail (mb);

  }


  // Send the message to the other thread.

  else

  {

   mb->wr_ptr (n);

   msg_queue->enqueue_tail (mb);

  }

 }

 // The destructor of Thread_Control removes

 // the exiting thread from the

 // Thread_Manager automatically.

 return 0;

}

static int consumer(MT_Message_Queue *msg_queue)

{

 ACE_Message_Block *mb = 0;

 // Insert thread into thr_mgr.

 ACE_Thread_Control tc (&thr_mgr);

 int result = 0;

 // Keep looping, reading a message out

 // of the queue, until we timeout or get a

 // message with a length == 0, which signals

 // us to quit.

 for (;;)

 {

  result = msg_queue->dequeue_head (mb);

  if (result == -1)

   return -1;

  int length = mb->length ();

  if (length > 0)

   ::write (1, mb->rd_ptr (), length);

  delete mb;

  if (length == 0)

   break;

 }


 // The destructor of Thread_Control removes

 // the exiting thread from the

 // Thread_Manager automatically.

 return 0;

}

int main (int argc, char *argv[])

{

 // Use the thread-safe instantiation

 // of Message_Queue.

 MT_Message_Queue msg_queue;


 thr_mgr.spawn (ACE_THR_FUNC (&producer),

  (void *) &msg_queue,

  THR_NEW_LWP | THR_DETACHED);

 thr_mgr.spawn (ACE_THR_FUNC (&consumer),

  (void *) &msg_queue,

  THR_NEW_LWP | THR_DETACHED);

 // Wait for producer/consumer threads to exit.

 thr_mgr.wait ();

 return 0;

}

Flask-SocketIO、message_queue和Redis通常结合在一起构建实时应用,如Web应用程序的消息推送系统。这里是一个简单的示例代码,展示了如何在Flask应用中使用Socket.IO连接客户端,并通过Redis作为消息队列: 首先安装所需的库: ```bash pip install Flask SocketIO redis ``` 然后创建`app.py`文件: ```python from flask import Flask, render_template from flask_socketio import SocketIO, emit import redis app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' socketio = SocketIO(app) # 连接Redis redis_client = redis.Redis(host='localhost', port=6379, db=0) @app.route('/') def index(): return render_template('index.html') @socketio.on('message') def handle_message(data): # 发送到Redis redis_client.rpush('message_queue', data) # 同步通知所有连接的客户端 emit('new_message', {'data': data}, broadcast=True) if __name__ == '__main__': socketio.run(app) ``` 在这个例子中,当用户发送一条`message`到前端页面时,服务端会将其存储到Redis的`message_queue`列表中,并立即广播给所有已连接的客户端。 接下来,假设你有`templates/index.html`,其中包含一个JS部分用于与Socket.IO交互: ```html <!DOCTYPE html> <html lang="en"> <head> <title>Real-time Chat</title> <script src="/socket.io/socket.io.js"></script> <script> const socket = io(); function sendMessage() { const input = document.getElementById('message-input'); socket.emit('message', input.value); input.value = ''; } // 接收新消息 socket.on('new_message', (data) => { console.log('New Message:', data.data); // 在这里添加显示新消息的逻辑 }); </script> </head> <body> <input type="text" id="message-input" placeholder="Type a message..."> <button onclick="sendMessage()">Send</button> </body> </html> ``` 在这个HTML中,每当用户输入并点击“Send”按钮,前端将向服务器发送一个消息,并接收新的消息更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值