5
That is the challenge:
Create a function that shows an item from a list every second. Using threads, make the program show all items as quickly as possible
My code:
import threading
import time
threads = int(input('Quantas threads você deseja? '))
lista = list(range(0, 50000))
if threads > len(lista):
threads = len(lista)
passo = len(lista) // threads
n = 0
n2 = passo
def thread(n, n2):
for i in lista[n:n2]:
print(i)
time.sleep(1)
for i in range(threads - 1):
threading.Thread(target=thread, args=(n, n2)).start()
n = n2
n2 += passo
threading.Thread(target=thread, args=(n, len(lista))).start()
It works, but the prints are not in order, there is some way to get them in order with the same efficiency or even more?
I also noticed that the work of each thread is different (the last thread usually has more items), so some end very quickly, and others very slowly. Is there any way to leave a number of threads "fixed" until the program lists all items?
could explain to me the use of threading.lock()?
– João
I edited adding a brief explanation with what I know. I’m sorry if it’s not enough for your problem, but my knowledge of
Threads
withLock
doesn’t go much further than that.– AlexCiuffa
like this method of adding threads in a list, I will definitely use
– João
Like the
total_valores
and thenum_threads
are fixed, would put their calculationtotal_valores/num_threads
out of the loop to avoid redoing it.– Gabriel Santos