如何在 python 的 "threading" 模块中指定线程数

How to specify the number of threads in python's "threading" module

我是 python 多线程编程的新手。但是为了 运行 我的功能在合理的时间内,我不得不使用它。 在在线教程中,我找到了这个基本代码:

import threading

    def f(id):
        print ("thread function:",id)
        return

    for i in range(3):
        t = threading.Thread(target=f, args=(i,))
        t.start()

我得到的输出是:

thread function: 0
thread function: 1
thread function: 2

在我的实际程序中,我有参数,是从本地文件中读取的一行。我想将它传递给目标函数。目标函数执行一些任务,然后将结果也写入本地文件。

我的问题: 1) 如何在上面的代码中指定线程数?

2) 目标函数将结果写入文件是否有问题?多个线程可以同时写入吗?有什么预防措施可以避免错误吗?

1) How can I specify the number of threads in the above code?

range 函数的参数是您的线程数。

2) Is there any problem in making the target function writes results to a file? Can the multiple threads write at the same time? Are there any precautions to take to avoid mistakes?

是的,如果您不小心管理 threader 函数正在使用的数据结构,python 中的多线程可能会非常奇怪。因此,在你的情况下,如果 write 操作不受控制,你可以让多个线程将同一行写入文件。也就是说,在您的情况下,您可能可以做的是将输入文件中的行放入 queue 然后 get threader 函数中的行并将其写入输出文件。