Python 运行 个线程顺序
Python running threads sequentially
我正在 Python 中试验 运行ning 代码并行。
我的用例如下:我有一个过程需要 运行 数千次。但由于它依赖于下载,我需要注意我同时 运行 的数量(我每分钟的请求数量有限)。因此,我总是希望同时 运行 该函数 10 次,每次完成后我都想启动一个新进程。
快速阅读后,线程模块似乎就是我要找的东西。但是,一些小实验似乎表明 Python 不会 运行 并行线程。
当我运行下面的代码
import threading
import time
wait = 0.4
def f(x):
for j in range(1,100):
time.sleep(wait)
print(x)
threading.Thread(target = f(1)).start()
threading.Thread(target = f(2)).start()
我进入命令行
1
1
1
1
1
在打印完所有 100 个之前,没有一个 2 出现。
这是怎么来的?理论上 f(1) 和 f(2) 应该同时 运行ning 对吗?
这一行
threading.Thread(target = f(1)).start()
基本上就是说"start a new thread and execute the result of f(1) in it".
你要的是"start a new thread and execute f with argument 1 in it",翻译过来就是
threading.Thread(target = f, args=(1,)).start()
我正在 Python 中试验 运行ning 代码并行。
我的用例如下:我有一个过程需要 运行 数千次。但由于它依赖于下载,我需要注意我同时 运行 的数量(我每分钟的请求数量有限)。因此,我总是希望同时 运行 该函数 10 次,每次完成后我都想启动一个新进程。
快速阅读后,线程模块似乎就是我要找的东西。但是,一些小实验似乎表明 Python 不会 运行 并行线程。
当我运行下面的代码
import threading
import time
wait = 0.4
def f(x):
for j in range(1,100):
time.sleep(wait)
print(x)
threading.Thread(target = f(1)).start()
threading.Thread(target = f(2)).start()
我进入命令行
1
1
1
1
1
在打印完所有 100 个之前,没有一个 2 出现。
这是怎么来的?理论上 f(1) 和 f(2) 应该同时 运行ning 对吗?
这一行
threading.Thread(target = f(1)).start()
基本上就是说"start a new thread and execute the result of f(1) in it".
你要的是"start a new thread and execute f with argument 1 in it",翻译过来就是
threading.Thread(target = f, args=(1,)).start()