如何 运行 同时使用 ThreadPoolExecutor
How to run concurrently using ThreadPoolExecutor
我已经使用 Threading 工作了一段时间,我设法发现在使用线程时我无法同时 运行。这是一个例子:
import concurrent.futures
import time
import random
from typing import List
site_catalog: List[str] = ["Thrill", "Test"]
def parse_value(value: str) -> None:
while True:
print("Caught: ", value)
time.sleep(random.randint(3, 5))
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for get_values in site_catalog:
executor.submit(parse_value(value=get_values))
>>> Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
我想知道如何才能同时 运行 列表中的值 site_catalog
?这意味着输出将类似于:
>>> Caught: Thrill
Caught: Test
Caught: Thrill
Caught: Test
Caught: Test
Caught: Thrill
Caught: Test
Caught: Thrill
Caught: Thrill
Caught: Test
Caught: Thrill
他们不依赖于彼此的执行
只需将其替换为:
executor.submit(parse_value(value=get_values))
至:
executor.submit(parse_value, get_values)
我已经使用 Threading 工作了一段时间,我设法发现在使用线程时我无法同时 运行。这是一个例子:
import concurrent.futures
import time
import random
from typing import List
site_catalog: List[str] = ["Thrill", "Test"]
def parse_value(value: str) -> None:
while True:
print("Caught: ", value)
time.sleep(random.randint(3, 5))
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for get_values in site_catalog:
executor.submit(parse_value(value=get_values))
>>> Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
Caught: Thrill
我想知道如何才能同时 运行 列表中的值 site_catalog
?这意味着输出将类似于:
>>> Caught: Thrill
Caught: Test
Caught: Thrill
Caught: Test
Caught: Test
Caught: Thrill
Caught: Test
Caught: Thrill
Caught: Thrill
Caught: Test
Caught: Thrill
他们不依赖于彼此的执行
只需将其替换为:
executor.submit(parse_value(value=get_values))
至:
executor.submit(parse_value, get_values)