samedi 20 août 2016

Print permutation of {0, 1, 2, 3} by multithread program (C++)

I want print a permutation of {0, 1, 2, 3} set by a multithread program written in C++11.

The source code is this:

#include <iostream>
#include <stdio.h>
#include <thread>
#include <vector>
#include <chrono>

using namespace std;


void func(int index);

int main()
{
    vector<thread> threads;

    for (int i = 0; i < 4; i++)
    {
        auto var = [&]()
        {
            return func(i);
        };

        threads.push_back(thread(var));
    }

    for (auto& thread : threads)
        thread.join();
}

void func(int index)
{
    cout << index;

    for (int i = 0; i < 10000; i++);
}

I expect in output a permutation of 0123, but I receive weird results, like these:

0223

0133

0124

I don't understand this weird behaviour, in particualar I cannot explain the presence of number 4.

Probably this is a beginner's mistake, I thanks anyway everybody will help me.

Aucun commentaire:

Enregistrer un commentaire