मल्टीथ्रेडिंग अवधारणाएं
मल्टीथ्रेडिंग लगभग सभी आधुनिक प्रोग्रामिंग भाषाओं की मूल अवधारणा है, विशेष रूप से पायथन की क्योंकि इसके थ्रेड्स का सरल कार्यान्वयन है।
एक थ्रेड एक प्रोग्राम के भीतर एक उप-प्रोग्राम है जिसे कोड के अन्य भागों से स्वतंत्र रूप से निष्पादित किया जा सकता है। एक थ्रेड प्रोग्राम के रनटाइम संसाधनों जैसे मेमोरी को साझा करते हुए समान संदर्भ में निष्पादित होता है।
जब एक ही प्रक्रिया में, हम एक साथ कई थ्रेड्स निष्पादित कर रहे होते हैं, तो इसे मल्टीथ्रेडिंग कहा जाता है।
थ्रेड कार्यान्वयन के लिए पायथन मल्टीथ्रेडिंग मॉड्यूल
प्रोग्राम में थ्रेड्स को लागू करने के लिए, पायथन दो मॉड्यूल प्रदान करता है:
- thread (पायथन 2.x के लिए) या _thread (पायथन 3.x के लिए) मॉड्यूल
- threading मॉड्यूल
जहां thread मॉड्यूल एक फ़ंक्शन के रूप में थ्रेड बनाता है, वहीं threading मॉड्यूल थ्रेड बनाने के लिए ऑब्जेक्ट-ओरिएंटेड दृष्टिकोण प्रदान करता है।
सिंटैक्स
_thread.start_new_thread(func, args[, kwargs])
उपरोक्त एक नया थ्रेड शुरू करता है और इसका पहचानकर्ता लौटाता है। पहला तर्क एक फ़ंक्शन func है जिसे थ्रेड दूसरे तर्क के साथ निष्पादित करता है जिसमें स्थितिगत तर्कों की सूची वाला एक टपल होता है। वैकल्पिक kwargs तर्क कीवर्ड तर्कों का एक शब्दकोश निर्दिष्ट करता है। जब फ़ंक्शन वापस लौटता है, तो थ्रेड चुपचाप समाप्त हो जाता है।
इसमें, हम क्लाइंट-सर्वर एप्लिकेशन का एक बुनियादी उदाहरण देखते हैं। जहां क्लाइंट मूल रूप से एक सॉकेट कनेक्शन खोलते हैं और सर्वर को क्वेरी भेजते हैं। सर्वर प्रतिक्रिया देता है।
बिना किसी तर्क के चलाने पर, यह प्रोग्राम एक TCP सॉकेट सर्वर के साथ शुरू होता है जो पोर्ट 8000 पर 127.0.0.1 पर कनेक्शन के लिए सुनता है।
client_thread1.py
import socket
import sys
def main():
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8000
try:
soc.connect((host, port))
except:
print("Connection Error")
sys.exit()
print("Please enter 'quit' to exit")
message = input(" -> ")
while message != 'quit':
soc.sendall(message.encode("utf8"))
if soc.recv(5120).decode("utf8") == "-":
pass # null operation
message = input(" -> ")
soc.send(b'--quit--')
if __name__ == "__main__":
main()
जबकि सर्वर प्रोग्राम है,
server_thread1.py
import socket
import sys
import traceback
from threading import Thread
def main():
start_server()
def start_server():
host = "127.0.0.1"
port = 8000 # मनमाना गैर-विशेषाधिकार पोर्ट
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Socket created")
try:
soc.bind((host, port))
except:
print("Bind failed. Error : " + str(sys.exc_info()))
sys.exit()
soc.listen(6) # 6 अनुरोधों तक कतार
print("Socket now listening")
# अनंत लूप - हर अनुरोध के लिए रीसेट न करें
while True:
connection, address = soc.accept()
ip, port = str(address[0]), str(address[1])
print("Connected with " + ip + ":" + port)
try:
Thread(target=client_thread, args=(connection, ip, port)).start()
except:
print("Thread did not start.")
traceback.print_exc()
soc.close()
def clientThread(connection, ip, port, max_buffer_size=5120):
is_active = True
while is_active:
client_input = receive_input(connection, max_buffer_size)
if "--QUIT--" in client_input:
print("Client is requesting to quit")
connection.close()
print("Connection " + ip + ":" + port + " closed")
is_active = False
else:
print("Processed result: {}".format(client_input))
connection.sendall("-".encode("utf8"))
def receive_input(connection, max_buffer_size):
client_input = connection.recv(max_buffer_size)
client_input_size = sys.getsizeof(client_input)
if client_input_size > max_buffer_size:
print("The input size is greater than expected {}".format(client_input_size))
decoded_input = client_input.decode("utf8").rstrip()
result = process_input(decoded_input)
return result
def process_input(input_str):
print("Processing the input received from client")
return "Hello " + str(input_str).upper()
if __name__ == "__main__":
main()
उपरोक्त स्क्रिप्ट चलाने पर, टर्मिनल में server_thread1.py चलाएं:
python server_thread1.py Socket created Socket now listening
हम सर्वर विंडो देखेंगे और प्रवाह को समझेंगे। अब कई क्लाइंट टर्मिनल खोलें, क्लाइंट थ्रेड चलाएं:
python client_thread1.py Enter 'quit' to exit -> Zack ->
दूसरे टर्मिनल में, एक और क्लाइंट प्रोग्राम चलाएं और सर्वर टर्मिनल विंडो भी देखें:
python client_thread1.py Enter 'quit' to exit -> Python -> quit
एक और टर्मिनल, क्लाइंट थ्रेड चलाएं:
python client_thread1.py Enter 'quit' to exit -> world! -> Anothny ->
और हम देख सकते हैं कि हमारी सर्वर विंडो इस तरह का आउटपुट प्रदर्शित करेगी:
Socket created Socket now listening Connected with 127.0.0.1:50275 Processing the input received from client Processed result: Hello ZACK Connected with 127.0.0.1:50282 Processing the input received from client Processed result: Hello PYTHON Processing the input received from client Client is requesting to quit Connection 127.0.0.1:50282 closed Connected with 127.0.0.1:50285 Processing the input received from client Processed result: Hello WORLD! Processing the input received from client Processed result: Hello ANOTHNY
तो थ्रेड्स कई सॉकेट कनेक्शन और क्लाइंट को संभालने के लिए सबसे आम तकनीकों में से एक प्रदान करते हैं।