When I have scripts that have to do extensive searching, I usually divide the work into threads with the help of the threading
. Since my main program is the one in charge of the searches, also this main program should be in charge of serving the results to the user, not the threads .
As an example, suppose I have a script, which is responsible for knowing if a number is within the range of 1 and 1 billion. Each thread is performing comparisons and might find the result.
My example script looks something like this:
import threading
def busqueda1(num):
for i in range(500000000):
if(num == i):
print("Busqueda1 confirmó el número")
def busqueda2(num):
for i in range(500000001,1000000000):
if(num == i):
print("Busqueda2 confirmó el número")
numero = 123456789
thread1 = threading.Thread(target=busqueda1,args=(numero,))
thread2 = threading.Thread(target=busqueda2,args=(numero,))
thread1.start()
thread2.start()
What I need is to know in my main program which of the two threads has found the number and show it to the user.
Since they are different execution threads, how do I make the main program and other threads have access to the possible results that are being generated?
From the official python 3.6 documentation we know that the object
Queue
:So the answer to this question is to use an object
Queue
to exchange information between threads. Briefly,Queue
it is an object that simulates a queue. When instantiated, it defaults to first-in-first-out, which indicates that the first object we put in the queue will be the first object we get when we try to get something out of it.The code would look something like this:
So instead of printing to the screen, threads queue the output they get and the main program can access this queue and get the information from there and print it.
This answer and question are inspired by this question from the English site.