এই টিউটোরিয়ালে আমরা পাইথনে মাল্টি-থ্রেডিং শিখব। এটি একসাথে একাধিক কাজ করতে সাহায্য করে। পাইথনে threading নামে একটি মডিউল রয়েছে মাল্টিটাস্কিং-এর জন্য।
আমরা দেখব কিভাবে একটি লিস্টের উপাদানগুলোর যোগফল বের করার সময় ব্যাকগ্রাউন্ডে ফাইলে ডেটা লিখা যায়। প্রোগ্রামের ধাপগুলো নিচে দেওয়া হলো।
- threading মডিউল ইম্পোর্ট করুন।
- 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(self.filename, 'w+') as file:
file.write(self.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()
It will run parallelly to the above task
Sum of numbers 1-5: 15
Finished writing to a file in background
আউটপুট
আপনি ডিরেক্টরি চেক করুন ফাইলের জন্য। উপরের কোড রান করলে নিচের আউটপুট मिलবে।
It will run parallelly to the above task Sum of numbers 1-5: 15 Finished writing to a file in background
উপসংহার
টিউটোরিয়াল সম্পর্কে কোনো প্রশ্ন থাকলে কমেন্ট সেকশনে জানান।