How to perform two functions, both containing infinite loop, simultaneously in Python?

Asked

Viewed 800 times

0

I have in the file Connections.py two functions, one where I am reading the 'status' field of a table every 1 second.

I also have another function in this same file doing the same process, but in another table.

Below, I list the contents of the file mentioned above (Connections.py)

import mysql.connector, time
import _thread as thread

db_connection = mysql.connector.connect(
  host="localhost",
  user="meuUsername",
  passwd="minhaSenha",
  database="meuBD"
)

my_database = db_connection.cursor()

def getTable1(): #Lê status de detecção / nome e identify
    while True:
        time.sleep(1)
        sql_statement = 'SELECT peopleId FROM detections where status = 1'
        my_database.execute(sql_statement)
        output = my_database.fetchall()
        print('Executando Thread getTable1()')

def getTable2():#lê status de reconhecimento
    while True:
        time.sleep(1)
        sql_statement = 'SELECT * FROM recognitions where status = 1'
        my_database.execute(sql_statement)
        output = my_database.fetchall()
        print('Executando Thread getTable2()')

In another file, called index.py, I am importing the contents of the file Connections.py and instantiating two threads, one for each reading function in the database.


import threading
import os, connections as cn

if __name__ == "__main__":

    processos = []
    processos.append(threading.Thread(target=cn.getStatusDetections()))
    processos.append(threading.Thread(target=cn.getStatusRecognitions()))
        # Ex: adicionar o porcesso `threading.Thread(target=inicia_programa, args=('x.py',))`

    for processo in processos:
        processo.start()

However, both threads are not executed at the same time and are executed in sequence, which results in never leaving the execution of the getTable1 function().

On the console is printed every second only:

Executando Thread getTable1() Executando Thread getTable1() Executando Thread getTable1() Executando Thread getTable1()

Being that I wish it were shown the result of the two so (no matter if it is in order):

Executando Thread getTable1() Executando Thread getTable2() Executando Thread getTable1() Executando Thread getTable2()

Would someone know to give me some knowledge on how to treat this in a way that works the execution of the two threads simultaneously?

2 answers

2


threading.Thread(target=cn.getStatusDetections())

Here you are calling the function cn.getStatusDetections and passing the return as target of thread. Since the function will never return, since it will be trapped in an infinite loop, the interpreter will not be able to evaluate the value of target, running this line eternally.

What you must go through as target is a reference to the function you want to perform, without parentheses.

threading.Thread(target=cn.getStatusDetections)

Thus the function will be executed within the thread.

About using the function print in threads, I suggest you read Problem with Python Thread Print

  • Good boy, that’s just what I needed. I’m glad it was such a silly thing kkkkk.

0

In addition to @Anderson’s reply Carlos Woss, mysql is kind of boring for mutual database access, it can return some error with two threads accessing it at the same time. In this case, I had to reserve the access of each thread to the database:

lock = threading.Lock() #Aqui instanciei essa variável

#Essa reserva de acesso usei dentro dos métodos de getTable1() e getTable2().
def getTable1():
    while True:
        lock.acquire() #Aqui reserva o acesso na porta para essa thrad.
        sql_statement = 'SELECT peopleId FROM detections where status = 1'
        my_database.execute(sql_statement)
        output = my_database.fetchall()
        if output: # se houve alteração do status,
            getPeople(output[0][0]) # executa função de encontrar a pessoa
        else: print('Detecção status = 0')
        lock.release() #Aqui libera o acesso na porta para outras Threads
        time.sleep(1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.