如何线程化整个函数?

How to thread an entire function?

我的目标是重写一个旧的代码库,使其具有同时下载 url 的功能,我想避免在该功能当前编码到程序中的任何地方都写 threading.Thread(target = func_that_downloads_things).start()

如果我可以只保留大部分读取 func_that_downloads_things() 的旧代码库(并将线程功能直接用于执行下载的一个函数),那就太棒了。

此代码同时下载所有 4 个网址:

import requests, threading, time

def func_that_downloads_things():
    request_method = 'GET'
    request_url = 'http://olympus.realpython.org/dice'
    r = requests.request(method=request_method, url=request_url, timeout=4)
    print(r.text + '... took ' + str(round(time.time() - thread_start_time, 4)) + " seconds to download... and threading.active_count() is at " + str(threading.active_count()))

#take the start time
thread_start_time = time.time()

#download 4 websites
threading.Thread(target = func_that_downloads_things).start()
threading.Thread(target = func_that_downloads_things).start()
threading.Thread(target = func_that_downloads_things).start()
threading.Thread(target = func_that_downloads_things).start()

#take the end time
thread_end_time = time.time()

#tell the world how long it took to start the threads and get to this point
print('took '+ str(round(thread_end_time - thread_start_time, 6)) + ' seconds to initiate all the downloads')

print("threading.active_count() is at " + str(threading.active_count()))

虽然此代码没有:

import requests, threading, time

def func_that_downloads_things(url):
    def dl(url):
        request_method = 'GET'
        request_url = url
        r = requests.request(method=request_method, url=request_url, timeout=4)
        print(r.text + '... took ' + str(round(time.time() - thread_start_time, 4)) + " seconds to download... and threading.active_count() is at " + str(threading.active_count()))
    threading.Thread(target = dl(url)).start()

#take the start time
thread_start_time = time.time()

#download 4 websites
func_that_downloads_things('http://olympus.realpython.org/dice')
func_that_downloads_things('http://olympus.realpython.org/dice')
func_that_downloads_things('http://olympus.realpython.org/dice')
func_that_downloads_things('http://olympus.realpython.org/dice')

#take the end time
thread_end_time = time.time()

#tell the world how long it took to start the threads and get to this point
print('took '+ str(round(thread_end_time - thread_start_time, 6)) + ' seconds to initiate all the downloads')

print("threading.active_count() is at " + str(threading.active_count()))

为什么?

替换

threading.Thread(target = dl(url)).start()

来自

threading.Thread(target = dl, args=(url,)).start()

您的代码在创建线程之前首先运行 dl(url),因为以这种方式编写它始终是对函数(或构造函数)的调用。

第二个代码只将未调用的函数对象连同参数一起传递给线程对象。然后在新创建的线程中使用给定的参数调用该函数。