samedi 28 septembre 2019

std::thread class member variable with unexpected behaviour

new to stackoverflow. I usually search and find all answers to my questions but for my current problem I couldn't find any help.
I introduced a std::thread member variable inside my Request class, which is supposed to work a routine in the background. The routine is sending a request, collecting the data and waiting a short amount of time before repeating. After the first iteration of the routine, other member variables of the class object change unexpectedly.

I had this request routine working before without the std::thread member variable. When I added the std::thread member variable, I had to delete the copy and the copy assignment member functions, because threads can't be copied. Even when commenting the sendRequest function and just sleeping, the request object gets modified. I've tried various different approaches of defining and initializing the std::thread class member.

    class Request { 
    public:
        Request() = default;
        Request(/*args*/);
        Request(const Request&) = delete;
        Request& operator=(const Request&) = delete;
        Request(Request&&) = default;
        Request& operator=(Request&&) = default;
        ~Request();
        bool active = true;
    private:
        void start();
        void routine();
        void sendRequest();
        std::thread requestRoutine;
        std::chrono::seconds sleepinterval;
        //std::queue<std::vector<std::pair<Query, json::value>>> responseQueue;
    }

    Request::Request(/*args*/)
        : requestRoutine()
    {
        /*init member variables*/
        start();
    }

    void Request::start()
    {
        requestRoutine = std::thread(&Request::routine, this);
        requestRoutine.detach();
    }

    void Request::routine()
    {
        while (this->active) {
            sendRequest();
            std::this_thread::sleep_for(sleepinterval);
        }
    }

I reduced the class to the important member functions and variables. If you are interested, I am using the cpprestsdk to send a HTTP request and i am receiving a HTTP response with a JSON object in the body. The most import includes for this file are the following:

#pragma once
#include <iostream>
#include <thread>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian_types.hpp"
#include <cpprest/http_listener.h>
#include <cpprest/http_client.h>
#include <cpprest/json.h>
#include <cpprest/filestream.h>

Any help and advice is much appreciated.
Thank you!

Aucun commentaire:

Enregistrer un commentaire