Насколько безопасен такой код? Есть ли ошибки?

Для проверки передачи данных между потоками написал такой код (обработка SIGINT пропущена для краткости):

#include <iostream>
#include <thread>
#include <atomic>
#include <array>
#include <condition_variable>
#include <chrono>
#include <queue>
#include <csignal>
#include <cstring>

using namespace std;

std::atomic_bool g_need_stop { false };
constexpr unsigned int BUF_SIZE { 256 };


unsigned char orig[BUF_SIZE] { 0xaa, 0x00, 0x13, 0x05, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0xf0, 0x00, 0xf0, 0xee, 0xc9, 0x00, 0x00, 0x55 };

unsigned char out[BUF_SIZE] { 0 };


void read_frame(atomic_bool& stop, mutex& mtx, condition_variable& condvar, queue<array<unsigned char, BUF_SIZE>>& que)
{
    unsigned char in[BUF_SIZE];

    while (!stop)
    {
        this_thread::sleep_for(chrono::milliseconds(640));

        memset(in, 0, BUF_SIZE);
        memcpy(in, orig, BUF_SIZE);

        unique_lock<mutex> lck(mtx);
        array<unsigned char, BUF_SIZE> arr;
        memcpy(arr.data(), in, BUF_SIZE);
        que.push(arr);
        cout << unitbuf << "Frame was sent" << endl;
        lck.unlock();
        condvar.notify_one();
    }
}


int main(int argc, char* argv[])
{
    mutex mut;
    condition_variable cv;
    queue<array<unsigned char, BUF_SIZE>> q;

    thread thr(read_frame, ref(g_need_stop), ref(mut), ref(cv), ref(q));

    while (!g_need_stop)
    {
        unique_lock<mutex> lck(mut);
        while (q.empty()) cv.wait(lck);

        array<unsigned char, BUF_SIZE> b = q.front();
        q.pop();
    }

    thr.join();

    return 0;
}

Код работает, но хотелось бы знать:

  • Хоть valgrind не находит утечек, есть ли потенциальные проблемы?
  • Нет ли ошибок, как его можно улучшить;

Ответы (0 шт):