首页 > 解决方案 > 线程在 Django 中被阻塞 - Python

问题描述

在过去的 4 个小时里,我一直在尝试理解 django 的线程。似乎没有任何效果。我想让网站在前台运行,让后端与线程上的其他一些设备通信。我希望线程在网站启动时启动,但是当我调用线程直到线程结束时程序卡住了。你知道修复它的方法吗?请我需要帮助。

urls.py 文件

def add(x, y):
    i=0

    while i < 100000000:
        x += y
        i += 1

def postpone(function):
    t = threading.Thread(target=function, args=(1,))
    t.setDaemon(True)
    t.start()
    return 0

print("Before thread")

postpone(add(4,4))

print("After thread")

在 while 循环完成之前,服务器不会启动。

感谢阅读,希望有人知道答案。

标签: python-3.xdjangomultithreading

解决方案


add在线程启动之前调用函数,但您需要add作为参考传递。

# decomposition 
# first, add gets called
r = add(4,4)
# then the result is passed to func `postpone`
postpone(r)

# postpone accept a function and args, which eventually get passed to the function
def postpone(function, *args):
    t = threading.Thread(target=function, args=args)
    t.setDaemon(True)
    t.start()
    return 0

print("Before thread")
# pass func as a reference, also send args to the postpone func also
postpone(add, 4,4)
print("After thread")

推荐阅读