Python Threading
In this page:
import threading
thread = threading.Thread(target=function_name, args=(arg,))
thread.start()
thread.join()
Threading क्या है?
Threading किसी program को एक ही process के अंदर कई हिस्से लगभग एक साथ चलाने देता है, जो I/O-bound tasks (network requests या disk reads का इंतज़ार करना) के लिए सबसे उपयोगी है जहाँ कोई thread बाकी program को block किए बिना idle रह सकता है -- CPU-bound काम को Python के GIL की वजह से इससे बहुत कम फ़ायदा मिलता है।
उदाहरण: What is Threading?
import threading
print(threading.active_count())
एक Basic Thread बनाना
Thread बनाने का मतलब है threading.Thread(target=some_function) को instantiate करना और फिर उस पर .start() call करना -- start() thread को आपके program के बाकी हिस्से के साथ concurrently चलते हुए launch करता है, न कि किसी normal function call की तरह उसे तुरंत चलाकर block करता है।
उदाहरण: Creating a Basic Thread
import threading
def task():
print("Running in a thread")
t = threading.Thread(target=task)
t.start() # starts running concurrently
t.join() # waits for the thread to finish
Threads को Join करना
डिफ़ॉल्ट रूप से, आपका main program thread के खत्म होने का इंतज़ार किए बिना start() के तुरंत बाद चलता रहता है -- किसी thread object पर .join() call करना calling code को तब तक block करता है जब तक वह specific thread पूरा न हो जाए, जो तब मायने रखता है जब बाद का code उस thread के काम के पूरे होने पर depend करता है।
उदाहरण: Joining Threads
import threading
def task():
print("Thread work done")
t = threading.Thread(target=task)
t.start()
t.join() # blocks here until the thread completes
print("Main continues after thread finishes")
Arguments के साथ Threading
Thread() का args parameter arguments का एक tuple स्वीकार करता है जिसे thread शुरू होने पर target function को पास किया जाता है -- Thread(target=download, args=(url,)) यही तरीका है जिससे आप download(url) को सीधे call करने की बजाय concurrently चलने के लिए launch करते हैं।
उदाहरण: Threading with Arguments
import threading
def greet(name):
print("Hello,", name)
t = threading.Thread(target=greet, args=("Alex",)) # args are passed to greet when the thread starts
t.start()
t.join()
Thread Safety और Locks
चूँकि एक ही process में threads memory share करते हैं, दो threads का एक ही moment पर एक ही variable बदलना उसे race condition के ज़रिए corrupt कर सकता है -- threading.Lock() आपको code के किसी हिस्से को mark करने देता है ताकि एक बार में सिर्फ़ एक thread उसे execute कर सके, जिससे ऐसा टकराव रुक जाता है।
उदाहरण: Thread Safety and Locks
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
with lock: # only one thread runs this block at a time
counter += 1
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: