Reputation: 2259
I'm new to python, so please excuse my ignorance. I am trying to get a process to run at the same time as my main file. The use case I have is that I want to alter the points of a game (adding/adjusting points for all users) at the same time that my flask/python app accepts CRUD requests. I could probably just schedule this for a midnight run or something, but in the future I may want to make multiple changes to the points depending on user input. Basically though, I really want to use some sort of threading feature.
Unfortunately, my thread blocks the operation of main. I'm not sure why, as I had thought that the threading's whole point was that it ran at the same time.
Here is how I call my function from main:
i = Inflate('pants')
i.timermethod()
Here is the class and method as I have defined them:
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)
The output is that "hello there pants" is printed 5 times before my main function executes, whereas I would expect/want "hello there pants" to be printed maybe once, see other output from main as it runs at the same time, and then "hello there pants" to continue executing.
Please let me know if you have any ideas, I am stuck.
Upvotes: 2
Views: 4115
Reputation: 1559
Sleep blocks. You need to execute timermethod from a separate thread.
try:
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
instead of:
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
from your main thread. You need to explicitly tell python to invoke timermethod in its own thread, otherwise it will run in main.
Upvotes: 2
Reputation: 4354
You call i.timermethod() which sleeps for 2 seconds 5 times before returning.
Upvotes: 1