#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#include <chrono>
#include <algorithm>

using namespace std;

const int NUM_THREADS = 5;
atomic<bool> choosing[NUM_THREADS];
atomic<int> number[NUM_THREADS];

// Utility: Get max ticket number
int get_max_ticket() {
    int max_val = 0;
    for (int i = 0; i < NUM_THREADS; ++i) {
        max_val = max(max_val, number[i].load());
    }
    return max_val;
}

// Bakery Lock
void lock(int id) {
    choosing[id] = true;
    cout << "Thread " << id << " is choosing a ticket...\n";
    number[id] = get_max_ticket() + 1;
    choosing[id] = false;

    cout << "Thread " << id << " got ticket #" << number[id] << " and is waiting to enter...\n";

    for (int j = 0; j < NUM_THREADS; ++j) {
        while (choosing[j]) {}  // wait while other thread is choosing
        while (number[j] != 0 &&
              (number[j] < number[id] ||
              (number[j] == number[id] && j < id))) {
            // Waiting for its turn
        }
    }
}

// Bakery Unlock
void unlock(int id) {
    number[id] = 0;
}

// Critical Section simulation
void critical_section(int id) {
    lock(id);

    cout << "Thread " << id << " is ENTERING critical section.\n";
    this_thread::sleep_for(chrono::milliseconds(rand() % 1500 + 500));
    cout << "Thread " << id << " is EXITING critical section.\n\n";

    unlock(id);
}

int main() {
    // Initialize
    for (int i = 0; i < NUM_THREADS; ++i) {
        choosing[i] = false;
        number[i] = 0;
    }

    // Launch threads
    vector<thread> threads;
    for (int i = 0; i < NUM_THREADS; ++i) {
        threads.emplace_back(critical_section, i);
        this_thread::sleep_for(chrono::milliseconds(300)); // simulate random arrival like customers
    }

    for (auto &t : threads) {
        t.join();
    }

    return 0;
}
