python - 线程不会在后台运行?
问题描述
当我打电话时my_batch.run_jobs()
,我的线程不会在后台运行。相反,它通过等待方法完成运行来同步运行。
对于上下文,我从.py
文件中调用此方法,并且该方法在类中。当我在这个文件/类之外运行相同的函数时,它在后台运行得很好。
# package_name/module_name.py
class BaseModel(Model):
class Meta:
database = get_db()
class Batch(BaseModel):
def run_jobs():
def sleeper():
sleep(999)
t = threading.Thread(target=sleeper)
#t.daemon = True #tried with/ without
t.start()
例如
my_batch = Batch()
my_batch.run_jobs()
#doesn't print until line above finishes
print("in progress")
解决方案
我更新了您的测试代码。它似乎按预期运行。
import time, threading
class BaseModel(): pass
# class Meta:
# database = get_db()
class Batch(BaseModel):
def run_jobs(self):
def sleeper(): # runs in background thread
for t in range(10):
print('<sleeper>', t)
time.sleep(.9)
t = threading.Thread(target=sleeper)
t.start()
# this runs same time as background thread (sleeper)
for t in range(10):
print('<rj>', t)
time.sleep(.8)
mybatch = Batch()
mybatch.run_jobs() # runs in main thread
# this loop runs after run_jobs completes
for t in range(5):
print('<main>', t)
time.sleep(1)
输出
<sleeper> 0
<rj> 0
<rj> 1
<sleeper> 1
<rj> 2
<sleeper> 2
<rj> 3
<sleeper> 3
<rj> 4
<sleeper> 4
<rj> 5
<sleeper> 5
<rj> 6
<sleeper> 6
<rj> 7
<sleeper> 7
<rj> 8
<rj> 9
<sleeper> 8
<main> 0
<sleeper> 9
<main> 1
<main> 2
<main> 3
<main> 4
- - 更新 - -
这是分成模块的相同代码:
-- 迈克.py
import time, threading
class BaseModel(): pass
# class Meta:
# database = get_db()
class Batch(BaseModel):
def run_jobs(self):
def sleeper(): # runs in background thread
for t in range(10):
print('<sleeper>', t)
time.sleep(.9)
t = threading.Thread(target=sleeper)
t.start()
# this runs same time as background thread (sleeper)
for t in range(10):
print('<rj>', t)
time.sleep(.8)
--threadchk.py(主脚本)
import mike
import time, threading
mybatch = mike.Batch()
mybatch.run_jobs() # runs in main thread
# this loop runs after method completes
for t in range(5):
print('<main>', t)
time.sleep(1)
输出与上一次运行相同
推荐阅读
- java - 为什么我的代码没有正确打印出最高和第一名?
- laravel - 按数字排序,即使列类型是字符串,Laravel
- python - 单击按钮时如何制作tkinter计数器
- nvidia - 错误:在 Ubuntu 上运行 nvidia deepstream 5.0 SDK
- sql - 选择大于特定值的第一个值
- java - Scanner 对象有一个类属性,而不是在代码初始化中
- javascript - Reactjs 功能组件中是否有 setState() 的同步替代方案
- excel - 选择过滤值并将选择应用于第二个工作簿中的不同过滤器
- javascript - 在 DOM 更新后运行的 React 钩子
- python - 使用断开连接的标准输入启动 Python 子进程