0

in the below code i am learning how to synchronize threads. i referred to several tutorials. as stated in the tutorials, i must use Lock() object so to call

.acquire() and .release()

I coded the below code but i always receive the following error: please tell me how to synchronize threads properly

  self._target(*self._args, **self._kwargs)
  File "m:\python lessons\ThreadsWithSync.py", line 42, in isNumPrime
      lock.acquire()
  NameError: name 'lock' is not defined
      lock.acquire()
      lock.acquire()
  NameError: name 'lock' is not defined

code:

import threading
from threading import Lock, Thread
import logging
import time
from random import seed
from random import randint

class ThreadsWithSync(threading.Thread):
    lock = Lock()
    def __new__(cls):
    """
    For object creation
    """
    print("cls: %s"%(cls))
    #cls.onCreateObject()
    instance = super(ThreadsWithSync, cls).__new__(cls)
    #print("instace: %s"%(instance.__repr__)) #activate this line whenever an informative and descriprtive text about the instance is needed to be displayed
    return instance
    
    def __init__(self):
    """
    For object initialization
    """
    #print("self: %s"%(self)) 
    threading.Thread.__init__(self) #to initialize the super class
    print("self: %s"%(self))
    #seed(.1) #when set to integer number, the randomly generated numbers will be the same. ommit this to get different random numbers each run.

    @classmethod
    def onCreateObject(cls):
    """
    This will be invoked once the creation procedure of the object begins.
    """

    def __repr__(self):
    """
    similar to toString in Java
    """
    return "\n__class__: " + repr(self.__class__) +"\n__new__:" + repr(self.__new__) + "\n__str__: " + repr(self.__str__) + "\n__sizeof__: " + repr(self.__sizeof__)
    
    def isNumPrime(self, targetNum):
    lock.acquire()
    if targetNum == 0 or targetNum == 1:
        print("thread name: %s targetNum passed to method, will return false: %s"%(threading.current_thread().name,targetNum))
        return False

    if targetNum == 2:
        print("targetNum passed to method will return true: %s"%(targetNum))
        return True

    isPrim = True
    for i in range(3,targetNum):
        #print("thread name: %s in loop: targetNum: %s"%(threading.current_thread().name,targetNum)) 
        if targetNum % i == 0:
            isPrim = False
            break
    print("%s-> is %s a prime : %s"%(threading.current_thread().name,targetNum, isPrim)) 
    return isPrim

    def spawnThread(self):
    if __name__ == "__main__":
        self.main()

    def main(self):
    while True:
        thread_1 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_1', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
        thread_2 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_2', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
        thread_3 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_3', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
        thread_4 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_4', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
        thread_1.start()
        thread_2.start()
        thread_3.start()
        thread_4.start()
        time.sleep(3)

t1 = ThreadsWithSync()
t1.spawnThread()
Amrmsmb
  • 1
  • 27
  • 104
  • 226

0 Answers0