首页 > 解决方案 > 为什么线程中调用函数的某些部分代码没有被执行

问题描述

我在网上找到了这段代码,在运行这段代码时,我发现print("This is awful {}".format(self))这部分没有被执行。但是,如果我在没有 if 的情况下运行,那么这两个函数都可以工作(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...

标签: pythonpython-multithreading

解决方案


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

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

推荐阅读