mardi 8 juin 2021

Unexpected behavior running multiple detached threads

I am trying to create a multi-threaded program that does some calculations. Here is an example of what I'm trying to do:

#include <list>
#include <iostream>
#include <thread>
using namespace std;
mutex mtx;
class fire {
    public:
    int th;
    fire(int thr) {
        this->th = thr;
    }
    void execute() {
        for(int x = 0; x < 10; x++) {
            mtx.lock();
            cout << "thread : " << this->th << " loop : " << x << endl;
            mtx.unlock();
        }
    }
    thread exec() {
        cout << "Execute\n";
        return thread([=] { execute(); } );
    }
};

int main(void) {
    list<fire> move;
    for(int x = 0; x < 8; x++) {
        move.push_back(fire(x));
    }
    for ( auto x : move) {
        thread z = x.exec();
        z.detach();
    }
    cout << "End\n";
}

The output is :

Execute
Execute
Execute
thread : 2 loop : 0
thread : 2 loop : 1
thread : 2 loop : 2
thread : 2 loop : 3
thread : 2 loop : 4
thread : 2 loop : 5
thread : 2 loop : 6
thread : 2 loop : 7
thread : 2 loop : 8
thread : 2 loop : 9
Execute
thread : 3 loop : 0
thread : 3 loop : 1
thread : Execute
4 loop : 2
thread : 4 loop : 3
Execute
thread : 5 loop : 0
thread : 5 loop : 1
Execute
Execute
End

As you can see this is not the expected behaviour and I am exhausted with Google searches. Why am I not seeing normal behavior from this simple piece of code?

Aucun commentaire:

Enregistrer un commentaire