简体   繁体   中英

Python Flask Application with Threads not running parallel

I am trying to build a Python program that sends data over UDP and has a website to make settings. For this program, I need a script to run a flask webserver and a script to pull data at the same time. I want to use threading to run the processes (Flask server and the data pull/send part) at the same time. Because I need to run the part to pull the data all the time, I made "While True:", so that it is always running But when I start my threads only the Thread to pull data is running. I think the problem is, that I don't really run 2 Threads at the same time. But I think with Threading it should be possible to run the flask Thread and the Data thread at the same time. But I can't get it to work and I can't figure out the problem.

This is the file where I'm trying to start both threads:

import threading
import time
import mainl
import webserver

class mydata(threading.Thread):
    def __init__(self, iD, name):
        threading.Thread.__init__(self)
        self.iD = iD
        self.name = name
    def run(self):
        mainl.mainloop()

class mywebserver(threading.Thread):
    def __init__(self, iD, name):
        threading.Thread.__init__(self)
        self.iD = iD
        self.name = name

    def run(self):
        webserver()

t1 = mydata(1, "t1")
t2 = mywebserver(2, "t2")
t2.start()
t1.start()

This is the file to pull data, which should always run, which is why i used "While True:":

def mainloop():
    while True:
        import data1
        import data2
        import data3

        ###UDP###
        ip_adress = "192.168.178.150"
        udp_port = 8888

        text = ""
        data1 = data1.daten()
        data2 = data2.daten()
        data3 = data3.daten()
        # print("Coin STR", coin)
        time.sleep(3)
        text = "data1   data2   data3"
        send.senden(ip_adress, udp_port, text)

I found the problem, the loop in the imports began while importing. So the program did not continue.

Now I run the imports in a main function.

For more information I can recommend this: https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM