কম্পিউটার টিউটোরিয়াল

পাইথনে থ্রেড সিঙ্ক্রোনাইজেশন


पाइथन के साथ प्रदान किया गया threading मॉड्यूल एक सरल-से-लागू लॉकिंग तंत्र शामिल करता है जो आपको थ्रेड्स को सिंक्रोनाइज़ करने की अनुमति देता है। एक नया लॉक Lock() मेथड को कॉल करके बनाया जाता है, जो नया लॉक लौटाता है।

नए लॉक ऑब्जेक्ट का acquire(blocking) मेथड थ्रेड्स को सिंक्रोनस रूप से चलाने के लिए मजबूर करने के लिए उपयोग किया जाता है। वैकल्पिक blocking पैरामीटर आपको यह नियंत्रित करने में सक्षम बनाता है कि थ्रेड लॉक प्राप्त करने के लिए प्रतीक्षा करता है या नहीं।

यदि blocking को 0 पर सेट किया जाता है, तो थ्रेड तुरंत 0 मान के साथ लौटता है यदि लॉक प्राप्त नहीं किया जा सकता है और 1 के साथ यदि लॉक प्राप्त किया गया था। यदि blocking को 1 पर सेट किया जाता है, तो थ्रेड ब्लॉक हो जाता है और लॉक जारी होने की प्रतीक्षा करता है।

नए लॉक ऑब्जेक्ट का release() मेथड लॉक को तब जारी करने के लिए उपयोग किया जाता है जब इसकी आवश्यकता नहीं रहती।

उदाहरण

#!/usr/bin/python import threading import time class myThread (threading.Thread):    def __init__(self, threadID, name, counter):       threading.Thread.__init__(self)       self.threadID = threadID       self.name = name       self.counter = counter    def run(self):       print "Starting " + self.name    # Get lock to synchronize threads       threadLock.acquire()       print_time(self.name, self.counter, 3)       # Free lock to release next thread       threadLock.release() def print_time(threadName, delay, counter):    while counter:       time.sleep(delay)       print "%s: %s" % (threadName, time.ctime(time.time()))       counter -= 1 threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads:    t.join() print "Exiting Main Thread"

जब उपरोक्त कोड निष्पादित किया जाता है, तो यह निम्नलिखित परिणाम उत्पन्न करता है −

Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread

  1. পাইথনে issuperset() ফাংশন

  2. পাইথনে লগিং (Logging) – সম্পূর্ণ গাইড

  3. পাইথন গ্লোবাল ইন্টারপ্রেটার লক (GIL) কী এবং কেন এটি 아직도 আছে?

  4. পাইথনে থ্রেডে এক্সসেপশন হ্যান্ডলিং