python - .start() 不会导致启动线程
问题描述
我正在学习python中的多线程。我创建了以下示例,但 .start() 从未启动线程。请让我知道如何解决这个错误
代码:
import threading
import time
import logging
class ThreadsSync:
def __new__(cls):
"""
this will be invoked once the creation procedure of the object begins
"""
instance = super(ThreadsSync,cls).__new__(cls)
return instance
def __init__(self):
"""
this will be invoked once the initialisation procedure of the object begins
"""
self.configLogging()
self.spawnThreads()
def configLogging(self):
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S")
logging.getLogger().setLevel("DEBUG")
def spawnThreads(self):
if __name__ == "__main__":
thread1 = threading.Thread(target=backgroundTask,args=(10,))
#thread2 = threading.Thread(target=backgroundTask, args=(20,))
thread1.start()
#thread2.start()
def backgroundTask(threadName,numOfLoops):
for i in numOfLoops:
print(threadName, "-"*22, time.time())
解决方案
有几个问题
- 帖子中的缩进似乎不正确
if __name__ == "__main__":
好像发错地方了,删了- 类从不被调用:在底部添加调用
- 将
Thread
输入更改为target=self.backgroundTask
- 改为
numOfLoops
_range(numOfLoops)
import threading
import time
import logging
class ThreadsSync:
def __new__(cls):
"""
this will be invoked once the creation procedure of the object begins
"""
instance = super(ThreadsSync,cls).__new__(cls)
return instance
def __init__(self):
"""
this will be invoked once the initialisation procedure of the object begins
"""
self.configLogging()
self.spawnThreads()
def configLogging(self):
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S")
logging.getLogger().setLevel("DEBUG")
def spawnThreads(self):
thread1 = threading.Thread(target=self.backgroundTask,args=(10,))
#thread2 = threading.Thread(target=backgroundTask, args=(20,))
thread1.start()
#thread2.start()
def backgroundTask(threadName,numOfLoops):
for i in range(numOfLoops):
print(threadName, "-"*22, time.time())
if __name__==‘__main__’:
ThreadsSync()
推荐阅读
- ios - iOS 上 WebGL 着色器中的莫名行为
- c++ - C++ & SDL 为什么直接处理我的对象而不是使用指针有时会导致视觉问题?
- ios - 在多个 UICollectionViews 中显示电影列表中的详细视图
- redis - redis中如何表示product_id和产品属性数据
- javascript - 将下拉框选择附加到文本框
- c# - 返回多行
- matlab - 在 MATLAB GUI 中进行函数计算后隐藏工作区中的特定变量
- java - 将图形(绘制)添加到预先存在的 JPanel
- python - Python UDP使用sendmsg设置TTL [Errno 22]无效参数
- python-3.x - Python - 从特定文件夹/子文件夹 AWS S3 下载数据