ในบทช่วยสอนนี้ เราจะเรียนรู้เกี่ยวกับมัลติเธรดใน 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 Tutorialspoint"
filename = "tutorialspoint.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
บทสรุป
หากคุณมีข้อสงสัยใดๆ จากบทแนะนำ โปรดระบุในส่วนความคิดเห็น