为什么线程中调用函数的某些代码未执行

时间:2019-02-16 09:22:47

标签: python python-multithreading

我在线上找到了此代码,并且在运行此代码时发现print("This is awful {}".format(self))这部分没有被执行。但是如果我 如果没有运行,则两个功能均正常工作(self.connecting())。我不知道为什么会这样。你能描述一下吗?

 class MyThread(Thread):
     def __init__(self, val):
        ''' Constructor. '''
        Thread.__init__(self)
        self.val = val



 def run(self):
     for i in range(1, self.val):
         print('Value %d in thread %s' % (i, self.getName()))
         self.printing_fun()
         # Sleep for random time between 1 ~ 3 second
         #secondsToSleep = randint(1, 5)

         #time.sleep(secondsToSleep)

 def connecting(self):
     print "Establishing connection right now........."

 def printing_fun(self):
     # if i run like self.connecting() without previous if then all are 
     working fine.
     if  self.connecting():
      print("This is awefull {}".format(self)) 

# Run following code when the program starts
if __name__ == '__main__':
   # Declare objects of MyThread class
   myThreadOb1 = MyThread(4)
   myThreadOb1.setName('Thread 1')

   myThreadOb2 = MyThread(4)
   myThreadOb2.setName('Thread 2')



# Start running the threads!
   myThreadOb1.start()
   myThreadOb2.start()

   # Wait for the thre`enter code here`ads to finish...
   myThreadOb1.join()
   myThreadOb2.join()

   print('Main Terminating...')

结果:

Value 1 in thread Thread 1
Establishing connection right now.........
Value 2 in thread Thread 1
Establishing connection right now.........
Value 3 in thread Thread 1
Establishing connection right now.........
Value 1 in thread Thread 2
Establishing connection right now.........
Value 2 in thread Thread 2
Establishing connection right now.........
Value 3 in thread Thread 2
Establishing connection right now.........
Main Terminating...

1 个答案:

答案 0 :(得分:1)

与线程无关。看这段代码:

def connecting(self):
     print "Establishing connection right now........."

def printing_fun(self):
     # if i run like self.connecting() without previous if then all are 
     # working fine.
     if  self.connecting():
      print("This is awefull {}".format(self)) 

self.connecting()没有return语句,因此python使其返回None

并且永远不会满足if None:条件:它永远不会进入if

connecting是某些连接过程的存根,但实现不正确。要正确存根,您应该使它返回真实的东西:

def connecting(self):
     print("Establishing connection right now.........")
     return True