TypicalAM / Yarilo

Wireless Network Traffic Decrypter & Packet Analyzer
https://yarilo.piaseczny.dev
7 stars 0 forks source link

Channel-based communication #4

Closed TypicalAM closed 11 months ago

TypicalAM commented 11 months ago

We can use something like channels to have the client take only one packet at a time in a concurrent-safe manner. This could be implemented nicely to create a smooth bytestream-based approach.

TypicalAM commented 11 months ago

Something along those lines:

template <typename T>
class Channel {
public:
    void send(const T& value) {
        {
            std::unique_lock<std::mutex> lock(mutex_);
            queue_.push(value);
        }
        condition_.notify_one();
    }

    T receive() {
        std::unique_lock<std::mutex> lock(mutex_);
        condition_.wait(lock, [this] { return !queue_.empty(); });

        T value = queue_.front();
        queue_.pop();
        return value;
    }

private:
    std::queue<T> queue_;
    std::mutex mutex_;
    std::condition_variable condition_;
};