M
M
Morrowind2021-06-20 00:47:22
Python
Morrowind, 2021-06-20 00:47:22

Why does a thread in Python run asynchronously?

Hey!
I have a little gag with Python threads.
I'm using the normal threading module to run a function as a "daemon". when starting the Flask server.
The function itself has logic inside it and a number of functions called by this logic mixed with each other.

It turns out that in the log I see a wild mixture of asynchronous function launches of all the logic that I registered.
Having tested running my function separately in parts and together without entering into threading, everything works fine.

My function does something like this (BE CAREFUL PSEUDOCODE):

def start()
if "файл есть" == 'файл есть':
  while True :
  записываем данные в файл с последней точки (вызываем функцию b1).
else:
 создаем файл (вызываем функцию a1)
 наполняем файл данными (вызываем функцию a2)
 логика проверки даты и времени в записях и т.д. (вызываем функцию a3)
 while True :
    бесконечный цикл наполнения файла последней информацией.(вызываем функцию b1)

flow1 = Thread(target=start, daemon=True)
flow1.start()


What I see in the logs when the stream is started: There is no file -> there is a file creation branch -> the information from the logical branch above appears in the log (the one where the file exists) O_o and starts filling with the latest data. (At the same time, there is a branch of the initial filling of the file with data.) Further, the creation-initial filling function is completed and the usual work of an endless cycle of updating continues.
As a result, the data is stupidly mixed into complete chaos, the logs have the same trouble, and then the cycle fills it normally as I need.

I would like to know how to manage this asynchrony when you have 1 total then 1 thread?
Or is there some nuance when working with internal functions?
I would be grateful for practical examples of solving a similar problem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Morrowind, 2021-06-20
@hekkaaa

The solution is the following. Found the answer in What is the best way to organize two threads of execution inside Flask?
The problem is that Flask already has a flow, and because of this, such parsley as mine happens. It turns out I already have 2 threads and Flask is already somehow spinning them.
Solution: Manually make a separate run() thread and your own

app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html')

flow1 = Thread(target=app.run)
flow2 = Thread(target=momowwind, daemon=True)

flow1.start()
flow2.start()

A
alfss, 2021-06-20
@alfss

  1. Run everything in debug and figure out why
  2. Refuse flows
  3. Re-architect solution

There are no problems in the pseudocode, so the real code is not like that. Or in additional functions there are cyclic calls.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question