python - 为什么线程中调用函数的某些部分代码没有被执行
问题描述
我在网上找到了这段代码,在运行这段代码时,我发现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...
解决方案
与线程无关。看看这段代码:
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
推荐阅读
- mysql - 在 Sequel Pro 中恢复已删除的行
- vba - 调用使用函数的子例程的按钮出现问题
- servicestack - ServiceStack.OrmLite:类名出现在不同命名空间时的表冲突
- sql-server - MSSQL 存储过程帮助比较日期
- java - 僵尸异常幸免于难
- c - 具有不同目录的 C makefile
- ruby-on-rails - Rails send_file 文件名 utf-8 在 Internet Explorer 中损坏
- c# - C#如何使一个对象在另一个类中可见
- html - 什么语言的 CSS 会减少我使用的代码量?
- docker - 构建 docker 映像而不生成中间“无”映像