vendredi 30 décembre 2016

Creating a class to store threads and calling them

Here is a simplified version of what I am trying to do:

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

class client {
public:
    client() {
        running = true;

        threads.push_back(std::thread(this->main, this));
        threads.push_back(std::thread(this->render, this));
    }

    ~client() {};
protected:
private:
    std::vector<std::thread> threads;
    std::mutex mtx;
    bool running;

    void main() {
        while(running) {
            mtx.lock();
            std::cout << "main" << std::endl;
            mtx.unlock();
        }
    }

    void render() {
        while(running) {
            mtx.lock();
            std::cout << "render" << std::endl;
            mtx.unlock();
        }
    }
};


int main() {
    client c;

    return 0;
}

In fact it actually starts to work, for a couple iterations and then it just crashs.


What I am trying to do is create a class that holds threads for the main loop(of the class), rendering, and a couple other things. However I cannot get this simplified version to work. I have tried using mutex to lock and unlock the threads, but didn't seem to help any. I do not know why it is not working, but I suspect that it is a result of the use of this in threads.push_back(std::thread(this->main, this));.

The current structure of the code doesn't have to remain... The only requirement is that uses one of it's own member functions as a thread (and that, that thread is stored in the class). I am not sure if this requires two classes or if my attempt to do it in one class was the correct approach. I have seen many examples of creating an object, and then calling a member that creates threads. I am trying to avoid this and instead create the threads within the constructor.

Side question: the output to the console doesn't always run as expected, I figured mutex would be the solution, yet the resulting code was unsatisfactory.

Aucun commentaire:

Enregistrer un commentaire