How to run multiple threads when one of the threads needs the result from one of the other threads

Bit of a confusing question. What I would like to do is speed up the process of this.

        yt_client = SoundHandler.YouTube(search=search)
        download_link_attempt = await yt_client.PlaySongByLink()
        search_url = yt_client.SearchURL()
        source, video_url = await yt_client.GetTopSearchResultAudioSource(search_url)
        yt_info, yt_info_embed = await yt_client.GetYouTubeInformation(video_url)

But on the fourth line I need the variable from the third line. Same with the fourth and fifth.

I have tried everything I thought of, but can’t seem to figure it out.

Answer

Given multiple threads in the program and one wants to safely communicate or exchange data between them.

Perhaps the safest way to send data from one thread to another is to use a Queue from the queue library. To do this, create a Queue instance that is shared by the threads. Threads then use put() or get() operations to add or remove items from the queue as shown in the code given below.

Example: (taken from here)

from queue import Queue
from threading import Thread
  
# A thread that produces data
def producer(out_q):
    while True:
        # Produce some data
        ...
        out_q.put(data)
          
# A thread that consumes data
def consumer(in_q):
    while True:
        # Get some data
        data = in_q.get()
        # Process the data
        ...
          
# Create the shared queue and launch both threads
q = Queue()
t1 = Thread(target = consumer, args =(q, ))
t2 = Thread(target = producer, args =(q, ))
t1.start()
t2.start()