0

¿Me podrían decir qué puedo cambiar de aquí para que haya alternancia estricta, o sea que bote un hilo a la vez? algo así:

  • hilo 1
  • hilo 2
  • hilo 1
  • hilo 2
#include <iostream>
#include <thread>

using namespace std;

bool flag[2] = { false, false };

int turn;

void func0() {
    for (int i = 0; i < 10; i++) {
        flag[0] = true;
        while (flag[1] == true) {
            if (turn != 0) {
                flag[0] = false;

                while (turn == 1) {
                }

                flag[0] = true;
            }
        }
cout << "hilo 1" << endl;
        turn = 1;
        flag[0] = false;
    }
}
void func1() {
    for (int i = 0; i < 10; i++) {
        flag[1] = true;
        while (flag[0] == true) {
            if (turn != 1) {
                flag[1] = false;
                while (turn == 0) {

                }
                flag[1] = true;
            }
        }
cout << "hilo 2" << endl;
        turn = 0;
        flag[1] = false;
    }
}

int main() {
    thread t1(func0);
    thread t2(func1);
    t1.join();
    t2.join();
    return 0;
}

1 respuesta 1

0

Tal y como tienes el código no lo conseguirás nunca:

  1. No llames a thread::join, ya que eso unirá el hilo de ejecución al hilo del programa: es decir, la llamada se volverá síncrona.
  2. No uses banderas booleanas, usa std::mutex, con uno basta.
  3. Debes dar tiempo a un hilo para que tome control del std::mutex cuando otro hilo lo libera, añade una espera.

Con esto, obtienes el resultado deseado:

#include <thread>
#include <mutex>
#include <iostream>
#include <chrono>

std::mutex m;

template <unsigned N>
void f()
{
    using namespace std::chrono_literals;

    for (int i = 0; i != 10; ++i)
    {
        m.lock();                          // Bloquear el mutex
        std::cout << "Hilo " << N << '\n'; // Trabajar
        m.unlock();                        // Liberar el mutex
        std::this_thread::sleep_for(50ms); // Esperar tras liberar el mutex
    }
}

int main()
{
    std::thread t1(f<1>), t2(f<2>);

    // Sin thread::join

    using namespace std::chrono_literals;
    std::this_thread::sleep_for(2s);

    return 0;
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.