import threading
import time

states = [False, False]
turn = 0

THREADS = 2
MAX_COUNT = 20_000
counter = 0


# Protocolo entrada
def entry_critical_section(i):
    global states
    global turn
    j = i ^ 1
    states[i] = True
    turn = j
    while states[j] and turn == j:
        pass


# Seccion critica
def critical_section(i):
    global counter
    #time.sleep(0.05)
    counter += 1
    #print("En hilo " + str(i) + ", n=" + str(counter))


# Protocolo salida
def exit_critical_section(i):
    global states
    states[i] = False


# Funcion hilo
def thread(i):
    for _ in range(MAX_COUNT//THREADS):
        entry_critical_section(i)  # Protocolo entrada
        critical_section(i)  # Seccion critica
        exit_critical_section(i)  # Protocolo salida


def main():
    # Array hilos
    threads = []
    # Bucle creacion hilos
    for i in range(THREADS):
        t = threading.Thread(target=thread, args=(i,))
        threads.append(t)
        t.start()  # start the thread
    # Bucle espera hilos
    for t in threads:
        t.join()
    print("Counter value: {} Expected: {}\n".format(counter, MAX_COUNT))


if __name__ == "__main__":
    main()
