इस ट्यूटोरियल में, हम पायथन में मल्टी-थ्रेडिंग के बारे में जानेंगे। यह हमें एक साथ कई काम करने में मदद करता है। पायथन में एक मॉड्यूल होता है जिसे थ्रेडिंग . कहा जाता है मल्टीटास्किंग के लिए।
हम देखते हैं कि किसी सूची में तत्वों के योग की गणना करते समय पृष्ठभूमि में फ़ाइल में डेटा लिखकर यह कैसे काम करता है। आइए कार्यक्रम में शामिल चरणों को देखें।
-
थ्रेडिंग मॉड्यूल आयात करें।
-
threading.Thread . इनहेरिट करके एक क्लास बनाएं कक्षा।
-
उपरोक्त वर्ग में रन विधि के अंदर फ़ाइल कोड लिखें।
-
आवश्यक डेटा प्रारंभ करें।
-
किसी सूची में संख्याओं के योग की गणना करने के लिए कोड लिखें।
उदाहरण
# 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
निष्कर्ष
यदि आपके पास ट्यूटोरियल से कोई प्रश्न हैं, तो उनका उल्लेख टिप्पणी अनुभाग में करें।