在本教程中,我们将学习Python中的多线程。它可以帮助我们一次执行多个任务。Python有一个称为多任务线程化的模块。
我们通过在后台将数据写入文件同时计算列表中元素的总和来了解其工作原理。让我们看看程序中涉及的步骤。
导入线程模块。
通过继承threading.Thread类创建一个类。
在上述类的run方法中编写文件代码。
初始化所需的数据。
编写代码以计算列表中的数字总和。
# importing the modules
import threading
# creating a class by inhering the threading.Thread base class
class MultiTask(threading.Thread):
def __init__(self, message, filename):
# invoking the Base class
threading.Thread.__init__(self)
# initializing the variables to class
self.message = message
self.filename = filename
# run method that invokes in background
def run(self):
# opening the file in write mode
with open(filename, 'w+') as file:
file.write(message)
print("Finished writing to a file in background")
# initial code
if __name__ == '__main__':
# initializing the variables
message = "We're from Nhooo"
filename = "nhooo.txt"
# instantiation of the above class for background writing
file_write = MultiTask(message, filename)
# starting the task in background
file_write.start()
# another task
print("It will run parallelly to the above task")
nums = [1, 2, 3, 4, 5]
print(f"Sum of numbers 1-5: {sum(nums)}")
# completing the background task
file_write.join()它将与上述任务并行运行
1-5的总和:15
完成在后台写入文件
输出结果
您可以检查目录中的文件。如果运行上面的代码,您将获得以下输出。
It will run parallelly to the above task Sum of numbers 1-5: 15 Finished writing to a file in background
如果您对本教程有任何疑问,请在评论部分中提及。