当其中一个线程需要其他线程之一的结果时如何运行多个线程
How to run multiple threads when one of the threads needs the result from one of the other threads
有点令人困惑的问题。
我想做的是加快这个过程。
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)
但是在第四行我需要第三行的变量。
与第四和第五相同。
我已经尝试了所有我能想到的,但似乎无法弄清楚。
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.
示例:(取自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()
有点令人困惑的问题。 我想做的是加快这个过程。
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)
但是在第四行我需要第三行的变量。 与第四和第五相同。
我已经尝试了所有我能想到的,但似乎无法弄清楚。
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.
示例:(取自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()