#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 15 21:01:17 2022

@author: ojacques
"""

from threading import Thread
import random
import sys
import os

NUM_VALUES = 1000
valores = []
somaTotal = 0
threaded_total = 0
threads = []
NUM_THREADS = 4

class Th(Thread):
    subtotal = 0

    def __init__ (self, num):
        sys.stdout.write("Iniciando thread numero " + str(num) + "\n")
        sys.stdout.flush()
        Thread.__init__(self)
        self.num = num

    def run(self):

        range_start =int(self.num * NUM_VALUES / NUM_THREADS)  #0,250,500,750
        range_end = int(((self.num + 1) * NUM_VALUES / NUM_THREADS) - 1) #249, 499,749, 999

        for i in range(range_start, range_end+1): # i desde range_start até range_end (inclusivo)
            self.subtotal += valores[i]
            if i==range_end:
                sys.stdout.write("Subtotal para thread " + str(self.num) + ": " + str(self.subtotal) + " (from " + str(range_start) + " to " + str(range_end) + ") FIM thread "+str(self.num)+"\n");
            else:
                sys.stdout.write("Subtotal para thread " + str(self.num) + ": " + str(self.subtotal) + " (from " + str(range_start) + " to " + str(range_end) + ")\n");
            sys.stdout.flush()

    def get_subtotal(self):
        return self.subtotal

#### O programa comeca aqui #####

os.system('clear') or None #limpa a tela

random.seed(80)
for i in range(NUM_VALUES): #0..999
    valores.append(random.randint(0,100))
print("Valores sorteados")
print(valores)
print("===================================================================================")
print("|Este programa utiliza quatro threads (0,1,2,3) para somar 1000 números aleatórios|")
print("|sendo que o thread 0 fica com os números de índice 0 a 249, 0 thread 1 com os    |")
print("|índices 250 a 499, e assim por diante para os demais threads,                    |")
print("|Observe que não dá para prever quail thread terminará primeiro. Execute o progra-|")
print("|ma várias vezes.                                                                 |")
print("===================================================================================")
input("\nPressione alguma tecla")

for i in range(NUM_VALUES):
    somaTotal += valores[i]

print("Soma total (sem usar threads): " + str(somaTotal))

for thread_number in range(NUM_THREADS):
    threads.insert(thread_number, Th(thread_number))
    threads[thread_number].start()

for thread_number in range(NUM_THREADS):
    threads[thread_number].join()
    threaded_total += threads[thread_number].get_subtotal()


print(f"Soma total (sem usar threads): {somaTotal}")
print(f"Threaded total: {threaded_total}")
