Doing endless loops using threads in python

My program is designed as follows:

  • The first part of the program receives real-time values ​​from the sensor and displays it using Matplotlib. This must be done for a long duration. In addition, it registers information in a database.
  • The second part is the IP camera. I have to get the data from the IP camera and display it. For display, the OpenCV imshow method is used. In addition, I save video from the IP camera.

Question: I have algorithms in place, the problem is that I need to run both of these loops. The condition is that I cannot exit any of them. Threading is now a good alternative for this, but I read about GIL, so how do I need to run two infinite loops?

 from multiprocessing import Process def methodA(): while TRUE: do something def methodB(): while TRUE: do something p=Process(target=methodA()) p.start() p1=Process(target=methodB()) p1.start() 

Now, when I start the p process, it starts execution, after which how to start p1 to start at the same time?

+7
python multithreading matplotlib opencv
source share
1 answer

As far as I understand your question, you have two different tasks that you want them to perform continuously. Now about your questions:

How do I start two endless loops?

You can create two different threads that will run these endless loops for you. The first thread will complete your task1, and the second will execute task2.

In addition, as soon as I start execution of a thread, how to execute another when the first thread runs continuously / endlessly?

If you use two different threads, you do not need to worry about this problem. If the threads do not share any resource, you do not need to worry about this fact. If you want to stop / pause one thread from another thread or vice versa, you can implement the mechanism using flags or locks. These questions will help in this case:

Is there a way to kill a thread in Python?

Why does the python threading.Thread object have a "start" but not a "stop"?

make-a-program-munltithreaded

Example example using streaming:

 from threading import Thread class myClassA(Thread): def __init__(self): Thread.__init__(self) self.daemon = True self.start() def run(self): while True: print 'A' class myClassB(Thread): def __init__(self): Thread.__init__(self) self.daemon = True self.start() def run(self): while True: print 'B' myClassA() myClassB() while True: pass 

For shared resources?

Use Locks for them. Here are some examples. One , two and How to synchronize threads in python?

what if i don't want to run it with classes? How to do this using only methods?

 from threading import Thread def runA(): while True: print 'A\n' def runB(): while True: print 'B\n' if __name__ == "__main__": t1 = Thread(target = runA) t2 = Thread(target = runB) t1.setDaemon(True) t2.setDaemon(True) t1.start() t2.start() while True: pass 
+18
source share

All Articles