我是Python新手,所以请原谅我的无知。我试图让一个进程与我的主文件同时运行。我的用例是,我想在我的 Flask/Python 应用程序接受 CRUD 请求的同时更改游戏的分数(为所有用户添加/调整分数)。我可以可能只是将其安排为午夜运行或其他事件,但将来我可能希望根据用户输入对点进行多次更改。但基本上,我真的想使用某种线程功能。
不幸的是,我的线程阻塞了main的操作。我不知道为什么,因为我认为线程的全部意义在于它同时运行。
这是我从 main 调用函数的方法:
i = Inflate('pants')
i.timermethod()
这是我定义的类和方法:
from flask_restful import abort, reqparse, Resource
from marshmallow import Schema, fields, ValidationError, pre_load
from flask import Flask, Blueprint, request, jsonify
from flask_cors import CORS, cross_origin
import psycopg2
import os
from os.path import join, dirname
import threading
from time import sleep
class Inflate:
def __init__(self, s):
self.s = s
def printtest(self):
print('insided the printtest for inflation')
def hello(self, h):
print h + self.s
def timermethod(self):
h="hello there "
for i in range(5):
t = threading.Thread(target=self.hello, args=(h,))
t.start()
sleep(2)
输出是在我的 main 函数执行之前打印了 5 次“hello therepts”,而我希望/希望“hellotherepants”可能被打印一次,请参阅 main 的其他输出,因为它同时运行时间,然后“你好裤子”继续执行。
如果您有任何想法,请告诉我,我被困住了。
最佳答案
sleep block 。您需要从单独的线程执行计时器方法。
尝试:
t = Thread(target=i.timermethod)
t.start()
print "i will print immediately"
# print test will run 5 times in 5 separate threads, once every 2 secs
而不是:
i.timermethod()
# print test will run 5 times in 5 separate threads, once every 2 secs
print "i have to wait for timermethod() to finish"
#code that gets blocked
来自你的主线程。你需要显式告诉python在它自己的线程中调用timermethod,否则它将在main中运行。
关于python - Python 中的线程 block Main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45107590/