在C++中实现类似Erlang的发送和接收,可以使用C++11引入的多线程库和智能指针等特性。具体实现步骤如下:
#include<queue>
#include <mutex>
#include<condition_variable>
template<typename T>
class MessageQueue {
public:
void push(T&& msg) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(std::move(msg));
cv_.notify_one();
}
bool pop(T& msg) {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] { return !queue_.empty(); });
msg = std::move(queue_.front());
queue_.pop();
return true;
}
private:
std::queue<T> queue_;
std::mutex mutex_;
std::condition_variable cv_;
};
#include<thread>
void sender(MessageQueue<std::string>& msg_queue) {
while (true) {
std::string msg;
std::cin >> msg;
msg_queue.push(std::move(msg));
}
}
void receiver(MessageQueue<std::string>& msg_queue) {
while (true) {
std::string msg;
msg_queue.pop(msg);
std::cout << "Received message: "<< msg<< std::endl;
}
}
int main() {
MessageQueue<std::string> msg_queue;
std::thread sender_thread(sender, std::ref(msg_queue));
std::thread receiver_thread(receiver, std::ref(msg_queue));
sender_thread.join();
receiver_thread.join();
return 0;
}
这样,在C++中就实现了类似Erlang的发送和接收功能。需要注意的是,这里只是一个简单的示例,实际应用中可能需要更多的错误处理和线程管理。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云