2

Ошибка:

Вызвано исключение по адресу 0x00DE3D56 в thread.exe: 0xC0000005: нарушение прав доступа при записи по адресу 0x07565C09.

Исключение происходит внутри функции this->queue.push(val);

Файл xmemory:

template<class _Objty,
    class... _Types>
    static void construct(_Alloc&, _Objty * const _Ptr, _Types&&... _Args)
    {   // construct _Objty(_Types...) at _Ptr // Тут вылазит исключение
    ::new (const_cast<void *>(static_cast<const volatile void *>(_Ptr)))
        _Objty(_STD forward<_Types>(_Args)...);
    }

Код

#include <string>
#include <atomic>
#include <mutex>
#include <thread>
#include <queue>
#include <condition_variable>

class BaseDumper 
{
public:
    BaseDumper();
    virtual ~BaseDumper();
    void Start();
    void Stop();
    void Add(int val);
private:
    std::atomic_bool started;
    std::queue<int> queue;
    std::queue<int> swap_queue;
    std::condition_variable cond_var;
    std::thread thread;
    std::mutex mutex;
};
BaseDumper::BaseDumper() :
    started(false)
{

}

BaseDumper::~BaseDumper()
{

}

void BaseDumper::Add(int val)
{
    std::lock_guard<std::mutex>(this->mutex);
    this->queue.push(val);
    this->cond_var.notify_all();
}

void BaseDumper::Start()
{
    this->started = true;
    this->thread = std::thread([this]()
    {
        while (this->started)
        {
            std::unique_lock<std::mutex> lock(this->mutex);
            while (this->queue.empty() && this->started)
            {
                this->cond_var.wait_for(lock, std::chrono::milliseconds(200));
            }
            this->swap_queue.swap(this->queue);
            lock.unlock();
            while(!this->swap_queue.empty())
            {
                this->swap_queue.pop();
            }           
        }
    });
}

void BaseDumper::Stop()
{
    this->started = false;
    if (this->thread.joinable())
    {
        this->thread.join();
    }
}

void work(BaseDumper* dumper)
{
    int n = 10000;
    while (--n)
    {
        dumper->Add(n);
    }
}

int main()
{
    BaseDumper* dumper = new BaseDumper;
    dumper->Start();

    std::thread thr([dumper]() { work(dumper); });
    thr.join();
    dumper->Stop();
    delete dumper;
    return 0;
}

1 ответ 1

4

Проблема заключается в доступе к this->queue из разных потоков без синхронизации. std::lock_guard<std::mutex>(this->mutex); создает временную переменную, которая сразу же уничтожается и потому никакой синхронизации при вызове queue.push на следующей строке не происходит. Соответственно для исправления достаточно сделать тут обычную переменную.

{
    std::lock_guard<std::mutex> const lock{this->mutex};
    this->queue.push(val);
}
this->cond_var.notify_all();

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.